added onClick events for marker-cluster #4

Merged
PxlLoewe merged 6 commits from 3-fix-aircraftmarkers-missionmarkers into main 2025-04-30 04:46:28 +00:00
11 changed files with 104 additions and 115 deletions

View File

@@ -24,7 +24,7 @@ export const useSmartPopup = () => {
export const calculateAnchor = ( export const calculateAnchor = (
id: string, id: string,
mode: "popup" | "marker", mode: "popup" | "marker",
ignoreMarker?: boolean, options?: { ignoreMarker?: boolean; ignoreCluster?: boolean },
) => { ) => {
const otherMarkers = document.querySelectorAll(".map-collision"); const otherMarkers = document.querySelectorAll(".map-collision");
// get markers and check if they are overlapping // get markers and check if they are overlapping
@@ -36,8 +36,9 @@ export const calculateAnchor = (
if (!otherMarkers || !ownMarker) return "topleft"; if (!otherMarkers || !ownMarker) return "topleft";
const marksersInCluster = Array.from(otherMarkers).filter((marker) => { const marksersInCluster = Array.from(otherMarkers).filter((marker) => {
if (mode === "popup" && marker.id === `marker-${id}`) return false; if (mode === "popup" && marker.id === `marker-domain-${id}`) return false;
if (ignoreMarker && marker.id.startsWith("marker")) return false; if (options?.ignoreMarker && marker.id.includes("marker")) return false;
if (options?.ignoreCluster && marker.id.includes("cluster")) return false;
const rect1 = (marker as HTMLElement).getBoundingClientRect(); const rect1 = (marker as HTMLElement).getBoundingClientRect();
const rect2 = (ownMarker as HTMLElement).getBoundingClientRect(); const rect2 = (ownMarker as HTMLElement).getBoundingClientRect();
@@ -76,12 +77,6 @@ export const calculateAnchor = (
centerOfOverlappingMarkers.x /= markersPosition.length; centerOfOverlappingMarkers.x /= markersPosition.length;
centerOfOverlappingMarkers.y /= markersPosition.length; centerOfOverlappingMarkers.y /= markersPosition.length;
if (id == "2") {
console.log("markersInCluser", marksersInCluster);
console.log("ownMarkerPosition", ownMarkerPosition);
console.log("centerOfOverlappingMarkers", centerOfOverlappingMarkers);
}
if (marksersInCluster.length > 1) { if (marksersInCluster.length > 1) {
if (centerOfOverlappingMarkers.y < ownMarkerPosition.y) { if (centerOfOverlappingMarkers.y < ownMarkerPosition.y) {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) { if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
@@ -107,24 +102,25 @@ export interface SmartPopupRef {
} }
export const SmartPopup = ( export const SmartPopup = (
props: PopupProps & { ignoreMarker?: boolean } & RefAttributes<LPopup> & { props: PopupProps &
RefAttributes<LPopup> & {
options?: { ignoreMarker?: boolean; ignoreCluster?: boolean };
smartPopupRef?: Ref<SmartPopupRef>; smartPopupRef?: Ref<SmartPopupRef>;
id: string; id: string;
wrapperClassName?: string; wrapperClassName?: string;
}, },
) => { ) => {
const [showContent, setShowContent] = useState(false); const [showContent, setShowContent] = useState(false);
const { smartPopupRef, id, className, wrapperClassName, ignoreMarker } = const { smartPopupRef, id, className, wrapperClassName, options } = props;
props;
const [anchor, setAnchor] = useState< const [anchor, setAnchor] = useState<
"topleft" | "topright" | "bottomleft" | "bottomright" "topleft" | "topright" | "bottomleft" | "bottomright"
>("topleft"); >("topleft");
const handleConflict = useCallback(() => { const handleConflict = useCallback(() => {
const newAnchor = calculateAnchor(id, "popup", ignoreMarker); const newAnchor = calculateAnchor(id, "popup", options);
setAnchor(newAnchor); setAnchor(newAnchor);
}, [id, ignoreMarker]); }, [id, options]);
useImperativeHandle(smartPopupRef, () => ({ useImperativeHandle(smartPopupRef, () => ({
handleConflict, handleConflict,

View File

@@ -1,4 +1,3 @@
import { popup } from "leaflet";
import { create } from "zustand"; import { create } from "zustand";
interface MapStore { interface MapStore {

View File

@@ -3,6 +3,7 @@ import { MissionOptionalDefaults } from "@repo/db/zod";
import { serverApi } from "helpers/axios"; import { serverApi } from "helpers/axios";
import { create } from "zustand"; import { create } from "zustand";
import { toast } from "react-hot-toast"; import { toast } from "react-hot-toast";
import axios from "axios";
interface MissionStore { interface MissionStore {
missions: Mission[]; missions: Mission[];
@@ -17,15 +18,8 @@ export const useMissionsStore = create<MissionStore>((set) => ({
missions: [], missions: [],
setMissions: (missions) => set({ missions }), setMissions: (missions) => set({ missions }),
createMission: async (mission) => { createMission: async (mission) => {
const res = await fetch("/api/mission", { const { data } = await serverApi.put<Mission>("/mission", mission);
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(mission),
});
if (!res.ok) return new Error("Failed to create mission");
const data = await res.json();
set((state) => ({ missions: [...state.missions, data] })); set((state) => ({ missions: [...state.missions, data] }));
return data; return data;
}, },

View File

@@ -1,32 +0,0 @@
import { create } from "zustand";
import { PrismaClient } from "@prisma/client";
interface ReportStore {
ownId: null | string;
reportOpen: boolean;
setReportOpen: (open: boolean) => void;
setOwnId: (id: string) => void;
}
export const useReportStore = create<ReportStore>((set) => ({
ownId: null,
reportOpen: false,
setReportOpen: (open: boolean) => set({ reportOpen: open }),
setOwnId: (id: string) => set({ ownId: id }),
}));
const prisma = new PrismaClient();
export const sendReport = async (receiverId: string, message: string) => {
try {
await prisma.reportMessage.create({
data: {
receiverId,
message,
},
});
} catch (error) {
console.error("Failed to send report:", error);
throw error;
}
};

View File

@@ -5,17 +5,11 @@ import { useSession } from "next-auth/react";
import { Fragment, useEffect, useRef, useState } from "react"; import { Fragment, useEffect, useRef, useState } from "react";
import { Dispatcher } from "dispatch/_components/navbar/_components/action"; import { Dispatcher } from "dispatch/_components/navbar/_components/action";
import { cn } from "helpers/cn"; import { cn } from "helpers/cn";
import { useReportStore } from "_store/reportStore"; import { getDispatcher } from "pilot/_components/navbar/action";
import { serverApi } from "helpers/axios";
export const getDispatcher = async () => {
const res = await serverApi.get<Dispatcher[]>(`/dispatcher`);
return res.data;
};
export const Chat = () => { export const Chat = () => {
const { setReportOpen } = useReportStore();
const { const {
setReportTabOpen,
chatOpen, chatOpen,
setChatOpen, setChatOpen,
sendMessage, sendMessage,
@@ -65,7 +59,7 @@ export const Chat = () => {
console.log("cleared"); console.log("cleared");
} }
}; };
}, [addTabValue, chats]); }, [addTabValue, chats, session.data?.user.id]);
return ( return (
<div className={cn("dropdown dropdown-right", chatOpen && "dropdown-open")}> <div className={cn("dropdown dropdown-right", chatOpen && "dropdown-open")}>
@@ -76,7 +70,7 @@ export const Chat = () => {
<button <button
className="btn btn-soft btn-sm btn-primary" className="btn btn-soft btn-sm btn-primary"
onClick={() => { onClick={() => {
setReportOpen(false); setReportTabOpen(false);
setChatOpen(!chatOpen); setChatOpen(!chatOpen);
if (selectedChat) { if (selectedChat) {
setChatNotification(selectedChat, false); setChatNotification(selectedChat, false);

View File

@@ -4,9 +4,9 @@ import { useSession } from "next-auth/react";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { Dispatcher } from "dispatch/_components/navbar/_components/action"; import { Dispatcher } from "dispatch/_components/navbar/_components/action";
import { cn } from "helpers/cn"; import { cn } from "helpers/cn";
import { useLeftMenuStore } from "_store/leftMenuStore";
import { getDispatcher } from "dispatch/_components/left/Chat";
import { serverApi } from "helpers/axios"; import { serverApi } from "helpers/axios";
import { getDispatcher } from "pilot/_components/navbar/action";
import { useLeftMenuStore } from "_store/leftMenuStore";
export const Report = () => { export const Report = () => {
const { setChatOpen, setReportTabOpen, reportTabOpen, setOwnId } = const { setChatOpen, setReportTabOpen, reportTabOpen, setOwnId } =

View File

@@ -224,7 +224,6 @@ const AircraftPopupContent = ({ aircraft }: { aircraft: Aircraft }) => {
}; };
const AircraftMarker = ({ aircraft }: { aircraft: Aircraft }) => { const AircraftMarker = ({ aircraft }: { aircraft: Aircraft }) => {
const aircrafts = useAircraftsStore((state) => state.aircrafts);
const [hideMarker, setHideMarker] = useState(false); const [hideMarker, setHideMarker] = useState(false);
const map = useMap(); const map = useMap();
const markerRef = useRef<LMarker>(null); const markerRef = useRef<LMarker>(null);
@@ -266,7 +265,7 @@ const AircraftMarker = ({ aircraft }: { aircraft: Aircraft }) => {
>("topleft"); >("topleft");
const handleConflict = useCallback(() => { const handleConflict = useCallback(() => {
const newAnchor = calculateAnchor(aircraft.id, "marker"); const newAnchor = calculateAnchor(`aircraft-${aircraft.id}`, "marker");
setAnchor(newAnchor); setAnchor(newAnchor);
}, [aircraft.id]); }, [aircraft.id]);
@@ -296,7 +295,7 @@ const AircraftMarker = ({ aircraft }: { aircraft: Aircraft }) => {
anchor: "topleft" | "topright" | "bottomleft" | "bottomright", anchor: "topleft" | "topright" | "bottomleft" | "bottomright",
) => { ) => {
return `<div return `<div
id="marker-${aircraft.id}" id="marker-aircraft-${aircraft.id}"
class="${cn( class="${cn(
"relative w-auto transform inline-flex items-center gap-2 px-2 z-100", "relative w-auto transform inline-flex items-center gap-2 px-2 z-100",
anchor.includes("right") && "-translate-x-full", anchor.includes("right") && "-translate-x-full",
@@ -332,7 +331,7 @@ const AircraftMarker = ({ aircraft }: { aircraft: Aircraft }) => {
data-id="${aircraft.id}" data-id="${aircraft.id}"
data-anchor-lat="${aircraft.location.lat}" data-anchor-lat="${aircraft.location.lat}"
data-anchor-lng="${aircraft.location.lng}" data-anchor-lng="${aircraft.location.lng}"
id="marker-domain-${aircraft.id}" id="marker-domain-aircraft-${aircraft.id}"
class="${cn( class="${cn(
"map-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none", "map-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
anchor.includes("left") && "-translate-x-1/2", anchor.includes("left") && "-translate-x-1/2",
@@ -356,7 +355,10 @@ const AircraftMarker = ({ aircraft }: { aircraft: Aircraft }) => {
/> />
{openAircraftMarker.some((m) => m.id === aircraft.id) && !hideMarker && ( {openAircraftMarker.some((m) => m.id === aircraft.id) && !hideMarker && (
<SmartPopup <SmartPopup
id={aircraft.id} options={{
ignoreCluster: true,
}}
id={`aircraft-${aircraft.id}`}
ref={popupRef} ref={popupRef}
position={[aircraft.location.lat, aircraft.location.lng]} position={[aircraft.location.lat, aircraft.location.lng]}
autoClose={false} autoClose={false}

View File

@@ -258,7 +258,10 @@ const MissionMarker = ({ mission }: { mission: Mission }) => {
>("topleft"); >("topleft");
const handleConflict = useCallback(() => { const handleConflict = useCallback(() => {
const newAnchor = calculateAnchor(mission.id.toString(), "marker"); const newAnchor = calculateAnchor(
`mission-${mission.id.toString()}`,
"marker",
);
setAnchor(newAnchor); setAnchor(newAnchor);
}, [mission.id]); }, [mission.id]);
@@ -288,7 +291,7 @@ const MissionMarker = ({ mission }: { mission: Mission }) => {
anchor: "topleft" | "topright" | "bottomleft" | "bottomright", anchor: "topleft" | "topright" | "bottomleft" | "bottomright",
) => { ) => {
return `<div return `<div
id="marker-${mission.id}" id="marker-mission-${mission.id}"
class="${cn( class="${cn(
"relative w-auto transform inline-flex items-center gap-2 px-2 z-100", "relative w-auto transform inline-flex items-center gap-2 px-2 z-100",
anchor.includes("right") && "-translate-x-full", anchor.includes("right") && "-translate-x-full",
@@ -318,7 +321,7 @@ const MissionMarker = ({ mission }: { mission: Mission }) => {
data-anchor-lat="${mission.addressLat}" data-anchor-lat="${mission.addressLat}"
data-anchor-lng="${mission.addressLng}" data-anchor-lng="${mission.addressLng}"
data-id="${mission.id}" data-id="${mission.id}"
id="marker-domain-${mission.id}" id="marker-domain-mission-${mission.id}"
class="${cn( class="${cn(
"map-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none", "map-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
anchor.includes("left") && "-translate-x-1/2", anchor.includes("left") && "-translate-x-1/2",
@@ -342,7 +345,10 @@ const MissionMarker = ({ mission }: { mission: Mission }) => {
/> />
{openMissionMarker.some((m) => m.id === mission.id) && !hideMarker && ( {openMissionMarker.some((m) => m.id === mission.id) && !hideMarker && (
<SmartPopup <SmartPopup
id={mission.id.toString()} options={{
ignoreCluster: true,
}}
id={`mission-${mission.id.toString()}`}
ref={popupRef} ref={popupRef}
position={[mission.addressLat, mission.addressLng]} position={[mission.addressLat, mission.addressLng]}
autoClose={false} autoClose={false}

View File

@@ -1,6 +1,7 @@
import { Mission } from "@repo/db"; import { Mission } from "@repo/db";
import { SmartPopup, useSmartPopup } from "_components/SmartPopup"; import { SmartPopup, useSmartPopup } from "_components/SmartPopup";
import { Aircraft, useAircraftsStore } from "_store/aircraftsStore"; import { Aircraft, useAircraftsStore } from "_store/aircraftsStore";
import { useMapStore } from "_store/mapStore";
import { useMissionsStore } from "_store/missionsStore"; import { useMissionsStore } from "_store/missionsStore";
import { import {
FMS_STATUS_COLORS, FMS_STATUS_COLORS,
@@ -22,6 +23,10 @@ const PopupContent = ({
missions: Mission[]; missions: Mission[];
}) => { }) => {
const { anchor } = useSmartPopup(); const { anchor } = useSmartPopup();
const { setOpenAircraftMarker, setOpenMissionMarker } = useMapStore(
(state) => state,
);
const map = useMap();
let borderColor = ""; let borderColor = "";
@@ -33,7 +38,9 @@ const PopupContent = ({
} }
} else if (anchor.includes("bottom")) { } else if (anchor.includes("bottom")) {
if (aircrafts.length > 0) { if (aircrafts.length > 0) {
borderColor = FMS_STATUS_TEXT_COLORS[aircrafts[0]!.fmsStatus] || "white"; borderColor =
FMS_STATUS_TEXT_COLORS[aircrafts[aircrafts.length - 1]!.fmsStatus] ||
"white";
} else if (missions.length > 0) { } else if (missions.length > 0) {
borderColor = MISSION_STATUS_TEXT_COLORS[missions[0]!.state]; borderColor = MISSION_STATUS_TEXT_COLORS[missions[0]!.state];
} }
@@ -44,7 +51,7 @@ const PopupContent = ({
<div className="relative flex flex-col text-white min-w-[200px]"> <div className="relative flex flex-col text-white min-w-[200px]">
<div <div
className={cn( className={cn(
"absolute w-[calc(100%+2px)] h-4 z-99", "absolute w-[calc(100%+2px)] h-4 z-99 pointer-events-none",
anchor.includes("left") ? "-left-[2px]" : "-right-[2px]", anchor.includes("left") ? "-left-[2px]" : "-right-[2px]",
anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]", anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]",
)} )}
@@ -69,9 +76,26 @@ const PopupContent = ({
)} )}
style={{ style={{
backgroundColor: MISSION_STATUS_COLORS[mission.state], backgroundColor: MISSION_STATUS_COLORS[mission.state],
cursor: "pointer",
}} }}
> >
<span className="mx-2 my-0.5"> <span
className="mx-2 my-0.5 flex-1 cursor-pointer"
onClick={() => {
setOpenMissionMarker({
open: [
{
id: mission.id,
tab: "home",
},
],
close: [],
});
map.setView([mission.addressLat, mission.addressLng], 12, {
animate: true,
});
}}
>
{mission.missionKeywordAbbreviation} {mission.missionKeywordAbbreviation}
</span> </span>
</div> </div>
@@ -79,10 +103,24 @@ const PopupContent = ({
{aircrafts.map((aircraft) => ( {aircrafts.map((aircraft) => (
<div <div
key={aircraft.id} key={aircraft.id}
className="relative w-auto inline-flex items-center gap-2 text-nowrap" className="relative w-auto inline-flex items-center gap-2 text-nowrap cursor-pointer"
style={{ style={{
backgroundColor: FMS_STATUS_COLORS[aircraft.fmsStatus], backgroundColor: FMS_STATUS_COLORS[aircraft.fmsStatus],
}} }}
onClick={() => {
setOpenAircraftMarker({
open: [
{
id: aircraft.id,
tab: "aircraft",
},
],
close: [],
});
map.setView([aircraft.location.lat, aircraft.location.lng], 12, {
animate: true,
});
}}
> >
<span <span
className="mx-2 my-0.5 text-gt font-bold" className="mx-2 my-0.5 text-gt font-bold"
@@ -178,36 +216,34 @@ export const MarkerCluster = () => {
} }
}); });
setCluster((prev) => { const clusterWithAvgPos = newCluster.map((c) => {
return prev.map((c) => { const aircraftPos = c.aircrafts.map((a) => [
const aircraftPos = c.aircrafts.map((a) => [ a.location.lat,
a.location.lat, a.location.lng,
a.location.lng, ]);
]); const missionPos = c.missions.map((m) => [m.addressLat, m.addressLng]);
const missionPos = c.missions.map((m) => [ const allPos = [...aircraftPos, ...missionPos];
m.addressLat,
m.addressLng,
]);
const allPos = [...aircraftPos, ...missionPos];
// Calculate the average position of all markers in the cluster // Calculate the average position of all markers in the cluster
const avgLat =
allPos.reduce((sum, pos) => sum + pos[0]!, 0) / allPos.length;
const avgLng =
allPos.reduce((sum, pos) => sum + pos[1]!, 0) / allPos.length;
return { const avgLat =
...c, allPos.reduce((sum, pos) => sum + pos[0]!, 0) / allPos.length;
lat: avgLat, const avgLng =
lng: avgLng, allPos.reduce((sum, pos) => sum + pos[1]!, 0) / allPos.length;
};
}); console.log(allPos, { avgLat, avgLng });
return {
...c,
lat: avgLat,
lng: avgLng,
};
}); });
if (zoom >= 9) { if (zoom >= 9) {
setCluster([]); setCluster([]);
} else { } else {
setCluster(newCluster); setCluster(clusterWithAvgPos);
} }
}; };
handleZoom(); handleZoom();
@@ -220,17 +256,18 @@ export const MarkerCluster = () => {
<> <>
{cluster.map((c, i) => ( {cluster.map((c, i) => (
<SmartPopup <SmartPopup
ignoreMarker options={{
ignoreMarker: true,
}}
id={`cluster-${i}`} id={`cluster-${i}`}
wrapperClassName="relative" wrapperClassName="relative"
key={i} key={i}
position={[c.lat, c.lng]} position={[c.lat, c.lng]}
autoPan={false} autoPan={false}
autoClose={false} autoClose={false}
className="w-[202px]"
> >
<div> <PopupContent aircrafts={c.aircrafts} missions={c.missions} />
<PopupContent aircrafts={c.aircrafts} missions={c.missions} />
</div>
</SmartPopup> </SmartPopup>
))} ))}
</> </>

View File

@@ -9,10 +9,3 @@ export interface Dispatcher {
name: string; name: string;
socketId: string; socketId: string;
} }
export const getDispatcher = async () => {
const res = await fetch(`
${process.env.NEXT_PUBLIC_DISPATCH_SERVER_URL}/dispatcher`);
const data = await res.json();
return data as Dispatcher[];
};

Binary file not shown.