Skip to content

Commit ebc75d9

Browse files
committed
Refactor navigation handling in Map component
1 parent 4249dc3 commit ebc75d9

File tree

2 files changed

+8
-12
lines changed

2 files changed

+8
-12
lines changed

apps/web/components/Map/Map.tsx

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,21 @@
33
import { useEffect } from "react";
44
import "./Map.css";
55
import { useRouter } from "next/navigation";
6-
import { onClick, onMoveEnd, onPointerMove } from "./utils/events";
6+
import { onClick, onMoveEnd, onPointerMove, setNavigator } from "./utils/events";
77
import { initMap } from "./utils/init";
88

99
export default function OMap() {
1010
const router = useRouter();
1111

1212
useEffect(() => {
13-
const onNavigate = (e: Event) => {
14-
const href = (e as CustomEvent<string>).detail;
15-
if (href) router.push(href);
16-
};
17-
window.addEventListener("sr24:navigate", onNavigate);
13+
setNavigator((href) => router.push(href));
1814

1915
const map = initMap();
2016
map.on(["moveend"], onMoveEnd);
2117
map.on("pointermove", onPointerMove);
2218
map.on("click", onClick);
2319

2420
return () => {
25-
window.removeEventListener("sr24:navigate", onNavigate);
2621
map.un(["moveend"], onMoveEnd);
2722
map.un("pointermove", onPointerMove);
2823
map.un("click", onClick);

apps/web/components/Map/utils/events.tsx

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@ import { addHighlightedPilot, clearHighlightedPilot } from "./pilotFeatures";
1414
import { initTrackFeatures } from "./trackFeatures";
1515

1616
export type NavigateFn = (href: string) => void;
17-
export function navigateTo(href: string) {
18-
window.dispatchEvent(new CustomEvent("sr24:navigate", { detail: href }));
17+
let navigate: NavigateFn | null = null;
18+
export function setNavigator(fn: NavigateFn) {
19+
navigate = fn;
1920
}
2021

2122
export function onMoveEnd(evt: BaseEvent | Event): void {
@@ -110,7 +111,7 @@ export async function onClick(evt: MapBrowserEvent): Promise<void> {
110111
}
111112

112113
if (!feature) {
113-
navigateTo(`/`);
114+
navigate?.(`/`);
114115
return;
115116
}
116117

@@ -126,7 +127,7 @@ export async function onClick(evt: MapBrowserEvent): Promise<void> {
126127

127128
if (id) {
128129
const strippedId = id.toString().replace(/^pilot_/, "");
129-
navigateTo(`/pilot/${strippedId}`);
130+
navigate?.(`/pilot/${strippedId}`);
130131
addHighlightedPilot(strippedId);
131132
}
132133
}
@@ -383,5 +384,5 @@ export function resetMap(): void {
383384
clickedFeature?.set("clicked", false);
384385
clickedFeature = null;
385386

386-
navigateTo(`/`);
387+
navigate?.(`/`);
387388
}

0 commit comments

Comments
 (0)