Splitted code for conflicting label to SmartPopup

This commit is contained in:
PxlLoewe
2025-04-15 22:46:17 -07:00
parent fd4be984b0
commit 166b78bfc3
4 changed files with 269 additions and 187 deletions

View File

@@ -0,0 +1,153 @@
import { cn } from "helpers/cn";
import { RefAttributes, useEffect, useImperativeHandle } from "react";
import { createContext, Ref, useContext, useState } from "react";
import { Popup, PopupProps, useMap } from "react-leaflet";
import { Popup as LPopup } from "leaflet";
const PopupContext = createContext({
anchor: "topleft",
});
export const useSmartPopup = () => {
const context = useContext(PopupContext);
if (!context) {
throw new Error("usePopup must be used within a PopupProvider");
}
return context;
};
export const useConflict = (id: string, mode: "popup" | "marker") => {
const otherMarkers = document.querySelectorAll(".map-collision");
// get markers and check if they are overlapping
const ownMarker =
mode === "popup"
? document.querySelector(`#popup-${id}`)
: document.querySelector(`#marker-${id}`);
if (!otherMarkers || !ownMarker) return "topleft";
const marksersInCluster = Array.from(otherMarkers).filter((marker) => {
if (mode === "popup" && marker.id === `marker-${id}`) return false;
const rect1 = (marker as HTMLElement).getBoundingClientRect();
const rect2 = (ownMarker as HTMLElement).getBoundingClientRect();
return !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
});
// get the center of all overlapping markers
const markersPosition = marksersInCluster.map((marker) => {
const rect = (marker as HTMLElement).getBoundingClientRect();
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
};
});
const ownMarkerBounds = (ownMarker as HTMLElement).getBoundingClientRect();
const ownMarkerPosition = {
x: ownMarkerBounds.left + ownMarkerBounds.width / 2,
y: ownMarkerBounds.top + ownMarkerBounds.height / 2,
};
const centerOfOverlappingMarkers = markersPosition.reduce(
(acc, pos) => {
if (acc.x === 0 && acc.y === 0) return pos;
return {
x: (acc.x + pos.x) / 2,
y: (acc.y + pos.y) / 2,
};
},
{
x: 0,
y: 0,
},
);
if (marksersInCluster.length > 1) {
if (centerOfOverlappingMarkers.y < ownMarkerPosition.y) {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
return "topright";
} else {
return "topleft";
}
} else {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
return "bottomright";
} else {
return "bottomleft";
}
}
} else {
// Default
return "topleft";
}
};
export interface SmartPopupRef {
handleConflict: () => void;
}
export const SmartPopup = (
props: PopupProps &
RefAttributes<LPopup> & {
smartPopupRef?: Ref<SmartPopupRef>;
id: string;
wrapperClassName?: string;
},
) => {
const { smartPopupRef, id, className, wrapperClassName } = props;
const [anchor, setAnchor] = useState<
"topleft" | "topright" | "bottomleft" | "bottomright"
>("topleft");
const handleConflict = () => {
const newAnchor = useConflict(id, "popup");
setAnchor(newAnchor);
};
useImperativeHandle(smartPopupRef, () => ({
handleConflict,
}));
const map = useMap();
useEffect(() => {
setTimeout(handleConflict, 50);
map.on("zoom", handleConflict);
return () => {
map.off("zoom", handleConflict);
};
}, [map, anchor]);
return (
<Popup {...props} className={cn("relative", wrapperClassName)}>
<div
className={cn(
"pointer-events-auto bg-base-100 relative",
anchor.includes("right") && "-translate-x-full",
anchor.includes("bottom") && "-translate-y-full",
className,
)}
>
<div
data-id={id}
id={`popup-${id}`}
className={cn(
"map-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
anchor.includes("left") && "-translate-x-1/2",
anchor.includes("top") && "-translate-y-1/2",
)}
/>
<PopupContext.Provider value={{ anchor: anchor }}>
{props.children}
</PopupContext.Provider>
</div>
</Popup>
);
};

View File

@@ -5,6 +5,7 @@ import { useMapStore } from "_store/mapStore";
import { Fragment, useCallback, useEffect, useRef, useState } from "react"; import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import { cn } from "helpers/cn"; import { cn } from "helpers/cn";
import { Cross, House, Minimize2, Route } from "lucide-react"; import { Cross, House, Minimize2, Route } from "lucide-react";
import { SmartPopup, useConflict, useSmartPopup } from "_components/SmartPopup";
export const FMS_STATUS_COLORS: { [key: string]: string } = { export const FMS_STATUS_COLORS: { [key: string]: string } = {
"0": "rgb(126,0,5)", "0": "rgb(126,0,5)",
@@ -32,216 +33,13 @@ export const FMS_STATUS_TEXT_COLORS: { [key: string]: string } = {
"9": "rgb(42,217,42)", "9": "rgb(42,217,42)",
}; };
const AircraftLabel = ({ aircraft }: { aircraft: Aircraft }) => { const AircraftPopupContent = ({ aircraft }: { aircraft: Aircraft }) => {
const aircrafts = useAircraftsStore((state) => state.aircrafts); const setOpenAircraftMarker = useMapStore(
const map = useMap(); (state) => state.setOpenAircraftMarker,
const markerRef = useRef<LMarker>(null);
const popupRef = useRef<LPopup>(null);
const { openAircraftMarker, setOpenAircraftMarker } = useMapStore(
(store) => store,
); );
const { anchor } = useSmartPopup();
useEffect(() => {
const handleClick = () => {
const open = openAircraftMarker.includes(aircraft.id);
if (open) {
setOpenAircraftMarker({
open: [],
close: [aircraft.id],
});
} else {
setOpenAircraftMarker({
open: [aircraft.id],
close: [],
});
}
};
markerRef.current?.on("click", handleClick);
return () => {
markerRef.current?.off("click", handleClick);
};
}, [markerRef.current, aircraft.id, openAircraftMarker]);
const [anchor, setAnchor] = useState<
"topleft" | "topright" | "bottomleft" | "bottomright"
>("topleft");
const handleLabelConflict = useCallback(() => {
const otherMarkers = document.querySelectorAll(".aircraft-collision");
// get markers and check if they are overlapping
const ownMarker = openAircraftMarker.includes(aircraft.id)
? document.querySelector(`#aircraft-popup-${aircraft.id}`)
: document.querySelector(`#aircraft-marker-${aircraft.id}`);
if (!otherMarkers || !ownMarker) return;
const marksersInCluster = Array.from(otherMarkers).filter((marker) => {
if (
openAircraftMarker.includes(aircraft.id) &&
marker.id === `aircraft-marker-${aircraft.id}`
)
return false;
const rect1 = (marker as HTMLElement).getBoundingClientRect();
const rect2 = (ownMarker as HTMLElement).getBoundingClientRect();
return !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
});
// get the center of all overlapping markers
const markersPosition = marksersInCluster.map((marker) => {
const rect = (marker as HTMLElement).getBoundingClientRect();
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
};
});
const ownMarkerBounds = (ownMarker as HTMLElement).getBoundingClientRect();
const ownMarkerPosition = {
x: ownMarkerBounds.left + ownMarkerBounds.width / 2,
y: ownMarkerBounds.top + ownMarkerBounds.height / 2,
};
const centerOfOverlappingMarkers = markersPosition.reduce(
(acc, pos) => {
if (acc.x === 0 && acc.y === 0) return pos;
return {
x: (acc.x + pos.x) / 2,
y: (acc.y + pos.y) / 2,
};
},
{
x: 0,
y: 0,
},
);
if (marksersInCluster.length > 1) {
if (centerOfOverlappingMarkers.y < ownMarkerPosition.y) {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
setAnchor("topright");
} else {
setAnchor("topleft");
}
} else {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
setAnchor("bottomright");
} else {
setAnchor("bottomleft");
}
}
} else {
// Default
setAnchor("topleft");
}
}, [openAircraftMarker, aircraft.id]);
useEffect(() => {
handleLabelConflict();
}, [aircrafts, openAircraftMarker]);
useEffect(() => {});
useEffect(() => {
setTimeout(() => {
handleLabelConflict();
}, 100);
map.on("zoom", handleLabelConflict);
return () => {
map.off("zoom", handleLabelConflict);
};
}, [map, openAircraftMarker]);
const getMarkerHTML = (
aircraft: Aircraft,
anchor: "topleft" | "topright" | "bottomleft" | "bottomright",
) => {
return `<div
class="${cn(
"relative w-[140px] transform flex items-center gap-2 px-2 z-100",
anchor.includes("right") && "-translate-x-full",
anchor.includes("bottom") && "-translate-y-full",
)}"
style="
background-color: ${FMS_STATUS_COLORS[aircraft.fmsStatus]};
${openAircraftMarker.includes(aircraft.id) ? "opacity: 0; pointer-events: none;" : ""}
">
<div
class="${cn(
"absolute w-4 h-4 z-99",
anchor.includes("left") ? "-left-[2px]" : "-right-[2px]",
anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]",
)}"
style="
${anchor.includes("left") ? `border-left: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-right: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
${anchor.includes("top") ? `border-top: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-bottom: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
"
></div>
<span
class="font-semibold text-xl"
style="color: ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};"
>
${aircraft.fmsStatus}
</span>
<span class="text-white text-[15px]">
${aircraft.bosName}
</span>
<div
data-aircraft-id="${aircraft.id}"
id="aircraft-marker-${aircraft.id}"
class="${cn(
"aircraft-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
anchor.includes("left") && "-translate-x-1/2",
anchor.includes("top") && "-translate-y-1/2",
)}"
></div>
</div>`;
};
return ( return (
<Fragment key={aircraft.id}> <>
<Marker
ref={markerRef}
position={[aircraft.location.lat, aircraft.location.lon]}
icon={
new DivIcon({
iconAnchor: [0, 0],
html: getMarkerHTML(aircraft, anchor),
})
}
/>
{openAircraftMarker.includes(aircraft.id) && (
<Popup
ref={popupRef}
position={[aircraft.location.lat, aircraft.location.lon]}
autoClose={false}
closeOnClick={false}
autoPan={false}
className={cn("relative")}
>
<div
className={cn(
"w-[200px] h-[150px] pointer-events-auto bg-base-100 relative",
anchor.includes("right") && "-translate-x-full",
anchor.includes("bottom") && "-translate-y-full",
)}
>
<div
data-aircraft-id={aircraft.id}
id={`aircraft-popup-${aircraft.id}`}
className={cn(
"aircraft-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
anchor.includes("left") && "-translate-x-1/2",
anchor.includes("top") && "-translate-y-1/2",
)}
/>
<div <div
className="absolute p-1 z-99 top-0 right-0 transform -translate-y-full bg-base-100 cursor-pointer" className="absolute p-1 z-99 top-0 right-0 transform -translate-y-full bg-base-100 cursor-pointer"
onClick={() => { onClick={() => {
@@ -317,22 +115,153 @@ const AircraftLabel = ({ aircraft }: { aircraft: Aircraft }) => {
</div> </div>
</div> </div>
</div> </div>
</div> </>
</Popup> );
};
const AircraftMarker = ({ aircraft }: { aircraft: Aircraft }) => {
const aircrafts = useAircraftsStore((state) => state.aircrafts);
const map = useMap();
const markerRef = useRef<LMarker>(null);
const popupRef = useRef<LPopup>(null);
const { openAircraftMarker, setOpenAircraftMarker } = useMapStore(
(store) => store,
);
useEffect(() => {
const handleClick = () => {
const open = openAircraftMarker.includes(aircraft.id);
if (open) {
setOpenAircraftMarker({
open: [],
close: [aircraft.id],
});
} else {
setOpenAircraftMarker({
open: [aircraft.id],
close: [],
});
}
};
markerRef.current?.on("click", handleClick);
return () => {
markerRef.current?.off("click", handleClick);
};
}, [markerRef.current, aircraft.id, openAircraftMarker]);
const [anchor, setAnchor] = useState<
"topleft" | "topright" | "bottomleft" | "bottomright"
>("topleft");
const handleConflict = () => {
const newAnchor = useConflict(aircraft.id, "marker");
setAnchor(newAnchor);
};
useEffect(() => {
handleConflict();
}, [aircrafts, openAircraftMarker]);
useEffect(() => {});
useEffect(() => {
setTimeout(() => {
handleConflict();
}, 100);
map.on("zoom", handleConflict);
return () => {
map.off("zoom", handleConflict);
};
}, [map, openAircraftMarker]);
const getMarkerHTML = (
aircraft: Aircraft,
anchor: "topleft" | "topright" | "bottomleft" | "bottomright",
) => {
return `<div
class="${cn(
"relative w-[140px] transform flex items-center gap-2 px-2 z-100",
anchor.includes("right") && "-translate-x-full",
anchor.includes("bottom") && "-translate-y-full",
)}"
style="
background-color: ${FMS_STATUS_COLORS[aircraft.fmsStatus]};
${openAircraftMarker.includes(aircraft.id) ? "opacity: 0; pointer-events: none;" : ""}
">
<div
class="${cn(
"absolute w-4 h-4 z-99",
anchor.includes("left") ? "-left-[2px]" : "-right-[2px]",
anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]",
)}"
style="
${anchor.includes("left") ? `border-left: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-right: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
${anchor.includes("top") ? `border-top: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-bottom: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
"
></div>
<span
class="font-semibold text-xl"
style="color: ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};"
>
${aircraft.fmsStatus}
</span>
<span class="text-white text-[15px]">
${aircraft.bosName}
</span>
<div
data-id="${aircraft.id}"
id="marker-${aircraft.id}"
class="${cn(
"map-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
anchor.includes("left") && "-translate-x-1/2",
anchor.includes("top") && "-translate-y-1/2",
)}"
></div>
</div>`;
};
return (
<Fragment key={aircraft.id}>
<Marker
ref={markerRef}
position={[aircraft.location.lat, aircraft.location.lon]}
icon={
new DivIcon({
iconAnchor: [0, 0],
html: getMarkerHTML(aircraft, anchor),
})
}
/>
{openAircraftMarker.includes(aircraft.id) && (
<SmartPopup
id={aircraft.id}
ref={popupRef}
position={[aircraft.location.lat, aircraft.location.lon]}
autoClose={false}
closeOnClick={false}
autoPan={false}
wrapperClassName="relative"
className="w-[200px] h-[150px]"
>
<AircraftPopupContent aircraft={aircraft} />
</SmartPopup>
)} )}
</Fragment> </Fragment>
); );
}; };
export const AircraftMarker = (props: any) => { export const AircraftLayer = () => {
const { openAircraftMarker, setOpenAircraftMarker } = useMapStore(
(state) => state,
);
const aircrafts = useAircraftsStore((state) => state.aircrafts); const aircrafts = useAircraftsStore((state) => state.aircrafts);
const map = useMap();
return aircrafts.map((aircraft) => ( // IDEA: Add Marker to Map Layer / LayerGroup
<AircraftLabel key={aircraft.id} aircraft={aircraft} /> return (
)); <>
{aircrafts.map((aircraft) => {
return <AircraftMarker key={aircraft.id} aircraft={aircraft} />;
})}
</>
);
}; };

View File

@@ -6,7 +6,7 @@ import { BaseMaps } from "dispatch/_components/map/BaseMaps";
import { ContextMenu } from "dispatch/_components/map/ContextMenu"; import { ContextMenu } from "dispatch/_components/map/ContextMenu";
import { MissionMarkers } from "dispatch/_components/map/MissionMarkers"; import { MissionMarkers } from "dispatch/_components/map/MissionMarkers";
import { SearchElements } from "dispatch/_components/map/SearchElements"; import { SearchElements } from "dispatch/_components/map/SearchElements";
import { AircraftMarker } from "dispatch/_components/map/AircraftMarker"; import { AircraftLayer } from "dispatch/_components/map/AircraftMarker";
export default ({}) => { export default ({}) => {
const { map } = useMapStore(); const { map } = useMapStore();
@@ -17,7 +17,7 @@ export default ({}) => {
<SearchElements /> <SearchElements />
<ContextMenu /> <ContextMenu />
<MissionMarkers /> <MissionMarkers />
<AircraftMarker /> <AircraftLayer />
</MapContainer> </MapContainer>
); );
}; };

Binary file not shown.