Fixed issue with map not loading, making SVG dynamically altered depending on the number of clues. then linking that to the clue pages

Grey = cant click
Red = current
Green = complete
blue = skipped?
This commit is contained in:
bobbert committed 2025-03-16 18:20:34 +00:00
1 parent 0269fdfe68
commit 727555e70f
8 files changed
+605 -270

No files matched your search

+3 -21
View File
@@ -4,6 +4,7 @@ import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { use } from "react"; // Add this import for React.use() import { use } from "react"; // Add this import for React.use()
import NavBar from "@/components/NavBar";
export default function TeamPage({ params }) { export default function TeamPage({ params }) {
const { status, data: session } = useSession(); const { status, data: session } = useSession();
@@ -276,27 +277,7 @@ export default function TeamPage({ params }) {
</div> </div>
{/* Replace the outdated navbar with the correct one */} {/* Replace the outdated navbar with the correct one */}
<div className="nav-bar"> <NavBar activeLink="team" teamData={team} />
<Link href="/map" className="nav-item">
<div className="nav-icon">🗺️</div>
<div className="nav-label">Map</div>
</Link>
<Link href="/stats" className="nav-item">
<div className="nav-icon">📊</div>
<div className="nav-label">Stats</div>
</Link>
<Link
href={team ? `/${team.id}` : "/team-selection"}
className="nav-item active"
>
<div className="nav-icon">👥</div>
<div className="nav-label">Team</div>
</Link>
<Link href="/leaderboard" className="nav-item">
<div className="nav-icon">🏆</div>
<div className="nav-label">Leaderboard</div>
</Link>
</div>
<style jsx>{` <style jsx>{`
.team-page { .team-page {
@@ -420,6 +401,7 @@ export default function TeamPage({ params }) {
width: 100%; /* Use 100% instead of 100vw to prevent overflow issues */ width: 100%; /* Use 100% instead of 100vw to prevent overflow issues */
box-sizing: border-box; /* Include padding in width calculation */ box-sizing: border-box; /* Include padding in width calculation */
z-index: 100; /* Ensure navbar is above other content */ z-index: 100; /* Ensure navbar is above other content */
margin: 0; /* Remove any margin that might be causing the gap */
} }
.nav-item { .nav-item {
+3 -1
View File
@@ -168,13 +168,15 @@
background-color: white; background-color: white;
border-top: 1px solid #ddd; border-top: 1px solid #ddd;
padding: 10px 0; padding: 10px 0;
position: sticky; /* Sticky positioning */ position: fixed; /* Changed from sticky to fixed */
bottom: 0; /* Stick to bottom */ bottom: 0; /* Stick to bottom */
left: 0; left: 0;
width: 100%; width: 100%;
box-sizing: border-box; box-sizing: border-box;
z-index: 100; /* Ensure it stays on top */ z-index: 100; /* Ensure it stays on top */
flex-shrink: 0; /* Prevent navbar from shrinking */ flex-shrink: 0; /* Prevent navbar from shrinking */
margin: 0; /* Added margin property */
height: auto; /* Added height property */
} }
.nav-item { .nav-item {
+247 -206
View File
@@ -10,6 +10,7 @@ import {
clearHuntTimer, clearHuntTimer,
formatElapsedTime, formatElapsedTime,
} from "@/utils/timerService"; } from "@/utils/timerService";
import { populateMap, updateCluePointStatus } from "@/utils/map-populate";
export default function MapPage() { export default function MapPage() {
const { data: session, status } = useSession(); const { data: session, status } = useSession();
@@ -39,197 +40,167 @@ export default function MapPage() {
// Hard redirect function (for when a full page reload is needed) // Hard redirect function (for when a full page reload is needed)
const hardRedirect = useCallback((url) => { const hardRedirect = useCallback((url) => {
if (typeof window !== "undefined" && isMounted.current) {
window.location.href = url; window.location.href = url;
}
}, []); }, []);
// Add function to fetch team hunt start time // Fetch team data for the current user
const fetchTeamHuntStartTime = useCallback(async () => {
try {
// First check localStorage for cached start time
const cachedStartTime = localStorage.getItem("teamHuntStartTime");
// If we have a cached time, use it
if (cachedStartTime) {
return cachedStartTime;
}
// Otherwise fetch from the server - use effectiveTeamId which is derived from session
const effectiveTeamId = session?.user?.teamId;
if (effectiveTeamId) {
const response = await fetch(
`/api/teams/${effectiveTeamId}/hunt-session`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
},
credentials: "include",
}
);
if (response.ok) {
const data = await response.json();
if (data.startTime) {
// Cache the start time for future use
localStorage.setItem("teamHuntStartTime", data.startTime);
return data.startTime;
}
}
}
// Fallback to current time if we couldn't get a start time
return new Date().toISOString();
} catch (error) {
console.error("Failed to fetch team hunt start time:", error);
return new Date().toISOString();
}
}, []); // No dependencies to avoid re-creation - we'll handle session internally
// IMPORTANT: Move fetchTeamData up here, before it's referenced in useEffect dependencies
const fetchTeamData = useCallback(async () => { const fetchTeamData = useCallback(async () => {
if (!isMounted.current) return;
try { try {
setLoading(true);
setError(null);
const response = await fetch("/api/user/team", { const response = await fetch("/api/user/team", {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate", "Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
},
credentials: "include",
});
if (response.status === 401) {
softRedirect("/login");
return null;
}
if (response.status === 404) {
softRedirect("/team-selection");
return null;
}
if (!response.ok) {
throw new Error("Failed to fetch team data");
}
const data = await response.json();
setTeamData(data);
return data;
} catch (err) {
console.error("Failed to fetch team data:", err);
setError(err.message);
return null;
}
}, [softRedirect]);
// Fetch all clues with their status
const fetchClues = useCallback(async () => {
try {
const response = await fetch("/api/clues", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
}, },
credentials: "include", credentials: "include",
}); });
if (!response.ok) { if (!response.ok) {
// Handle specific error cases without immediate redirect throw new Error("Failed to fetch clues");
const errorData = await response.json().catch(() => ({}));
if (response.status === 401) {
// Set error but don't redirect immediately - let the session handling take care of it
setError(
"Authentication error: " + (errorData.error || "Not logged in")
);
setLoading(false);
return;
} else if (
response.status === 404 ||
errorData.error?.includes("not part of a team")
) {
setError("You need to join a team before viewing the map");
setLoading(false);
// Give user time to read the error message before redirect
setTimeout(() => {
if (isMounted.current) {
softRedirect("/team-selection");
}
}, 2000);
return;
} else {
throw new Error(errorData.error || "Failed to fetch team data");
}
} }
const data = await response.json(); const data = await response.json();
if (isMounted.current) {
setTeamData(data);
setLoading(false);
}
} catch (err) {
console.error("Error fetching team data:", err);
if (isMounted.current) {
setError(err.message);
setLoading(false);
}
}
}, [softRedirect]);
// Function to fetch clues // Process the clues to determine which are available
const fetchClues = useCallback(async () => { // A clue is available if it's either found already or the next in sequence
try { const processedClues = data.map((clue, index, arr) => {
const response = await fetch("/api/clues", { // Find the first unfound clue's index
headers: { "Cache-Control": "no-cache, no-store, must-revalidate" }, const firstUnfoundIndex = arr.findIndex((c) => !c.found);
credentials: "include",
// A clue is available if:
// 1. It's already found, OR
// 2. It's the next unfound clue in the sequence
const available = clue.found || index === firstUnfoundIndex;
return { ...clue, available };
}); });
if (response.ok) { setClues(processedClues);
const cluesData = await response.json(); return processedClues;
setClues(cluesData); } catch (err) {
} console.error("Failed to fetch clues:", err);
} catch (error) { setError(err.message);
console.error("Failed to fetch clues:", error); return [];
} }
}, []); }, []);
// Function to load and enhance the SVG map // Function to load and enhance the SVG map
const loadAndEnhanceMap = useCallback(async () => { const loadAndEnhanceMap = useCallback(async () => {
try { try {
// Fetch the SVG file
const response = await fetch("/images/map.svg"); const response = await fetch("/images/map.svg");
if (!response.ok) { if (!response.ok) {
console.error(
"Failed to load SVG:",
response.status,
response.statusText
);
setMapError(true); setMapError(true);
return; return;
} }
const svgText = await response.text(); const svgText = await response.text();
setMapSvg(svgText); console.log("SVG loaded, length:", svgText.length);
// Ensure SVG has correct namespaces and viewBox
let fixedSvg = svgText.replace(
/<svg/,
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"'
);
// Ensure SVG has a proper viewBox attribute if missing
if (!fixedSvg.includes('viewBox="')) {
const widthMatch = fixedSvg.match(/width="([^"]+)"/);
const heightMatch = fixedSvg.match(/height="([^"]+)"/);
if (widthMatch && heightMatch) {
const width = widthMatch[1];
const height = heightMatch[1];
fixedSvg = fixedSvg.replace(
/<svg/,
`<svg viewBox="0 0 ${width} ${height}"`
);
}
}
setMapSvg(fixedSvg);
setLoading(false);
} catch (error) { } catch (error) {
console.error("Failed to load map SVG:", error); console.error("Failed to load map SVG:", error);
setMapError(true); setMapError(true);
setLoading(false);
} }
}, []); }, []);
// Function to enhance SVG with clickable areas // Enhanced function to populate the map with clue points
const enhanceSvgMap = useCallback(() => { const enhanceSvgMap = useCallback(() => {
if (!mapContainerRef.current || !clues.length) return; if (!mapContainerRef.current) return;
// Find all circles in the SVG // Find the SVG element inside the map container
const circleSvgElements = const svgElement = mapContainerRef.current.querySelector("svg");
mapContainerRef.current.querySelectorAll("circle"); if (!svgElement) {
console.log(`Found ${circleSvgElements.length} circles in SVG`); console.error("No SVG element found in map container");
return;
// Find the highest available clue ID (first unfound clue)
let nextAvailableClueIndex = clues.findIndex((clue) => !clue.found);
if (nextAvailableClueIndex === -1) {
// If all clues are found, allow access to all
nextAvailableClueIndex = clues.length;
} }
// Convert NodeList to Array for easier manipulation console.log("SVG element found, starting enhancement");
Array.from(circleSvgElements).forEach((circle, index) => {
// Only process if we have a clue for this index and it's within bounds
if (index < clues.length) {
// Map SVG circle at position index to the clue at index
// This uses sequential order rather than coordinates
const clue = clues[index];
// Check if this clue is available (either found or next in sequence) // Use our utility to populate the map with clue points
const isAvailable = clue.found || index <= nextAvailableClueIndex; populateMap(svgElement)
.then((success) => {
if (success) {
console.log("Map populated successfully");
// After populating the map, update the status of each clue point
updateCluePointStatus(svgElement, clues);
// Add click handlers to each clue point
const cluePoints = svgElement.querySelectorAll(".clue-point");
cluePoints.forEach((circle, index) => {
if (index < clues.length) {
const clue = clues[index];
const isAvailable = clue.available;
// Make circle interactive // Make circle interactive
circle.style.cursor = isAvailable ? "pointer" : "not-allowed"; circle.style.cursor = isAvailable ? "pointer" : "not-allowed";
// Set appropriate colors // Add click handler
if (clue.found) {
// Found clues are green
circle.style.fill = "#4caf50";
circle.style.stroke = "#2e7d32";
} else if (isAvailable) {
// Next available clue is orange
circle.style.fill = "#ff9800";
circle.style.stroke = "#d87f00";
} else {
// Unavailable clues are grey
circle.style.fill = "#9e9e9e";
circle.style.stroke = "#757575";
}
circle.style.strokeWidth = "2";
// Add click handler to navigate to the clue page, but only if available
circle.onclick = (e) => { circle.onclick = (e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@@ -259,7 +230,7 @@ export default function MapPage() {
} }
}; };
// Add tooltip/title with actual clue ID and position information // Add tooltip with clue information
const label = document.createElementNS( const label = document.createElementNS(
"http://www.w3.org/2000/svg", "http://www.w3.org/2000/svg",
"title" "title"
@@ -270,69 +241,16 @@ export default function MapPage() {
circle.appendChild(label); circle.appendChild(label);
} }
}); });
} else {
console.error("Failed to populate map");
}
})
.catch((error) => {
console.error("Error enhancing SVG map:", error);
setMapError(true);
});
}, [clues, router]); }, [clues, router]);
// Clean up function for unmounting
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
// Initial hunt status check
useEffect(() => {
// Check if hunt is active
checkHuntAndTimer();
// Set up periodic checks
const interval = setInterval(checkHuntAndTimer, 3000);
return () => clearInterval(interval);
}, []);
// Handle authentication and hunt status
useEffect(() => {
// Only redirect if explicitly not authenticated
if (status === "unauthenticated") {
softRedirect("/login");
return;
}
// If hunt is not active, redirect to waiting page
if (huntActive === false) {
console.log("Hunt is not active, redirecting to waiting page");
softRedirect("/waiting");
return;
}
// Only fetch team data if authenticated and hunt is active or status unknown
if (status === "authenticated" && huntActive !== false) {
fetchTeamData();
loadAndEnhanceMap();
fetchClues();
}
}, [
status,
huntActive,
softRedirect,
fetchTeamData,
loadAndEnhanceMap,
fetchClues,
]);
// Add effect to enhance SVG once it's loaded and clues are fetched
useEffect(() => {
if (mapSvg && clues.length > 0) {
console.log("SVG and clues loaded, enhancing map...");
// Let the DOM update first with the SVG content
const enhanceTimeout = setTimeout(() => {
enhanceSvgMap();
}, 200);
return () => clearTimeout(enhanceTimeout);
}
}, [mapSvg, clues, enhanceSvgMap]);
// Function to check hunt status and timer // Function to check hunt status and timer
async function checkHuntAndTimer() { async function checkHuntAndTimer() {
if (!isMounted.current) return; if (!isMounted.current) return;
@@ -404,6 +322,77 @@ export default function MapPage() {
} }
} }
// Add this function before it's used in initializeTimer
async function fetchTeamHuntStartTime() {
try {
// First get the user's team ID
const userResponse = await fetch("/api/user", {
method: "GET",
headers: {
"Cache-Control": "no-store, no-cache, must-revalidate",
Pragma: "no-cache",
},
credentials: "include",
});
if (!userResponse.ok) {
console.error("Failed to fetch user data:", userResponse.statusText);
return null;
}
const userData = await userResponse.json();
const teamId = userData.teamId;
if (!teamId) {
console.error("User does not belong to a team");
return null;
}
// Now fetch the team's hunt session using the team ID
const teamHuntResponse = await fetch(
`/api/teams/${teamId}/hunt-session`,
{
method: "GET",
headers: {
"Cache-Control": "no-store, no-cache, must-revalidate",
Pragma: "no-cache",
},
credentials: "include",
}
);
if (!teamHuntResponse.ok) {
console.error(
"Failed to fetch team hunt session:",
teamHuntResponse.statusText
);
// Try the global hunt timer as fallback
const globalResponse = await fetch("/api/hunt/timer", {
method: "GET",
headers: {
"Cache-Control": "no-store, no-cache, must-revalidate",
Pragma: "no-cache",
},
credentials: "include",
});
if (globalResponse.ok) {
const globalData = await globalResponse.json();
return globalData.startTime || null;
}
return null;
}
const teamHuntData = await teamHuntResponse.json();
return teamHuntData.startTime || null;
} catch (error) {
console.error("Error fetching team hunt start time:", error);
return null;
}
}
// Use team hunt start time for elapsed time calculation // Use team hunt start time for elapsed time calculation
useEffect(() => { useEffect(() => {
// Initialize the timer without waiting for teamData // Initialize the timer without waiting for teamData
@@ -533,6 +522,57 @@ export default function MapPage() {
return () => clearInterval(intervalId); return () => clearInterval(intervalId);
}, [softRedirect, hardRedirect]); }, [softRedirect, hardRedirect]);
// Add this useEffect to coordinate loading the map and clues
useEffect(() => {
// Only proceed if authenticated
if (status === "authenticated") {
const initMap = async () => {
try {
// Set loading state
setLoading(true);
// Load both map and clues in parallel
await Promise.all([fetchClues(), loadAndEnhanceMap()]);
// Data is loaded, we'll let the next effect handle enhancement
} catch (error) {
console.error("Error initializing map data:", error);
setError("Failed to load map data");
setLoading(false);
}
};
initMap();
} else if (status === "unauthenticated") {
router.push("/login");
}
}, [status, fetchClues, loadAndEnhanceMap, router]);
// Modified useEffect to better handle SVG loading and enhancement
useEffect(() => {
// Only try to enhance the map if both the SVG and clues are loaded
if (!mapSvg || !clues.length) return;
console.log("Both SVG and clues loaded, enhancing map");
// Use requestAnimationFrame to ensure the DOM has been updated with the SVG
requestAnimationFrame(() => {
// Short timeout to ensure the SVG is fully rendered in the DOM
setTimeout(() => {
if (
mapContainerRef.current &&
mapContainerRef.current.querySelector("svg")
) {
console.log("SVG found in DOM, enhancing map");
enhanceSvgMap();
} else {
console.error("SVG not found in DOM after rendering");
setMapError(true);
}
}, 100);
});
}, [mapSvg, clues, enhanceSvgMap]);
if (status === "loading" || loading) { if (status === "loading" || loading) {
return ( return (
<div className={styles["loading-container"]}> <div className={styles["loading-container"]}>
@@ -588,13 +628,14 @@ export default function MapPage() {
<div className={styles["team-code"]}>{teamData?.team?.code || ""}</div> <div className={styles["team-code"]}>{teamData?.team?.code || ""}</div>
</div> </div>
{/* Main map content area - now allows scrolling with right alignment */} {/* Main map content area */}
<div className={styles["map-container"]} ref={mapContainerRef}> <div className={styles["map-container"]} ref={mapContainerRef}>
<div className={styles["treasure-map"]}> <div className={styles["treasure-map"]}>
{mapSvg ? ( {mapSvg ? (
<div <div
className={styles["svg-container"]} className={styles["svg-container"]}
dangerouslySetInnerHTML={{ __html: mapSvg }} dangerouslySetInnerHTML={{ __html: mapSvg }}
onLoad={() => console.log("SVG container loaded")}
/> />
) : ( ) : (
<div <div
@@ -606,7 +647,7 @@ export default function MapPage() {
</div> </div>
</div> </div>
{/* Navigation bar at the bottom */} {/* Navigation bar */}
<nav className={styles["nav-bar"]}> <nav className={styles["nav-bar"]}>
<Link <Link
href="/map" href="/map"
+6 -2
View File
@@ -369,8 +369,7 @@ export default function TeamPage({ params }) {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-height: 100vh; min-height: 100vh;
background-color: #f4f4f4; padding-bottom: 70px; /* Add space for the navbar */
font-family: Arial, sans-serif;
} }
.team-banner { .team-banner {
@@ -475,6 +474,11 @@ export default function TeamPage({ params }) {
background-color: white; background-color: white;
border-top: 1px solid #ddd; border-top: 1px solid #ddd;
padding: 10px 0; padding: 10px 0;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
z-index: 100;
} }
.nav-item { .nav-item {
BIN
View File
Binary file not shown.
+90
View File
@@ -0,0 +1,90 @@
"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import styles from "@/app/(main)/map/map.module.css";
export default function NavBar({ activeLink, teamData }) {
const [huntActive, setHuntActive] = useState(null);
const router = useRouter();
// Check if hunt is active
useEffect(() => {
const checkHuntStatus = async () => {
try {
const timestamp = Date.now();
const response = await fetch(`/api/hunt-status?t=${timestamp}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store, no-cache, must-revalidate",
Pragma: "no-cache",
},
credentials: "include",
});
if (response.ok) {
const data = await response.json();
setHuntActive(data.active);
}
} catch (err) {
console.error("Failed to check hunt status:", err);
}
};
checkHuntStatus();
}, []);
// Handle map link click
const handleMapClick = (e) => {
if (huntActive === false) {
e.preventDefault();
router.push("/waiting");
}
};
return (
<nav className={styles["nav-bar"]}>
<Link
href="/map"
className={`${styles["nav-item"]} ${
activeLink === "map" ? styles["active"] : ""
}`}
onClick={handleMapClick}
>
<div className={styles["nav-icon"]}>🗺️</div>
<div className={styles["nav-label"]}>Map</div>
</Link>
<Link
href="/stats"
className={`${styles["nav-item"]} ${
activeLink === "stats" ? styles["active"] : ""
}`}
>
<div className={styles["nav-icon"]}>📊</div>
<div className={styles["nav-label"]}>Stats</div>
</Link>
<Link
href={teamData?.team ? `/${teamData.team.id}` : "/team-selection"}
className={`${styles["nav-item"]} ${
activeLink === "team" ? styles["active"] : ""
}`}
>
<div className={styles["nav-icon"]}>👥</div>
<div className={styles["nav-label"]}>Team</div>
</Link>
<Link
href="/leaderboard"
className={`${styles["nav-item"]} ${
activeLink === "leaderboard" ? styles["active"] : ""
}`}
>
<div className={styles["nav-icon"]}>🏆</div>
<div className={styles["nav-label"]}>Leaderboard</div>
</Link>
</nav>
);
}
+40 -40
View File
@@ -23,84 +23,84 @@
<rect x="181" y="1974" width="88" height="88" fill="url(#pattern10_37_192)"/> <rect x="181" y="1974" width="88" height="88" fill="url(#pattern10_37_192)"/>
<rect x="373" y="1512" width="88" height="88" fill="url(#pattern11_37_192)"/> <rect x="373" y="1512" width="88" height="88" fill="url(#pattern11_37_192)"/>
<g filter="url(#filter0_d_37_192)"> <g filter="url(#filter0_d_37_192)">
<circle cx="230" cy="211" r="25" fill="#A5D6A7"/> <circle cx="230" cy="211" r="25" fill="#9e9e9e"/>
<circle cx="230" cy="211" r="25" stroke="black" stroke-width="2"/> <circle cx="230" cy="211" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter1_d_37_192)"> <g filter="url(#filter1_d_37_192)">
<circle cx="320" cy="284" r="25" fill="#A5D6A7"/> <circle cx="320" cy="284" r="25" fill="#9e9e9e"/>
<circle cx="320" cy="284" r="25" stroke="black" stroke-width="2"/> <circle cx="320" cy="284" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter2_d_37_192)"> <g filter="url(#filter2_d_37_192)">
<circle cx="264" cy="397" r="25" fill="#A5D6A7"/> <circle cx="264" cy="397" r="25" fill="#9e9e9e"/>
<circle cx="264" cy="397" r="25" stroke="black" stroke-width="2"/> <circle cx="264" cy="397" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter3_d_37_192)"> <g filter="url(#filter3_d_37_192)">
<circle cx="342" cy="517" r="25" fill="#A5D6A7"/> <circle cx="342" cy="517" r="25" fill="#9e9e9e"/>
<circle cx="342" cy="517" r="25" stroke="black" stroke-width="2"/> <circle cx="342" cy="517" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter4_d_37_192)"> <g filter="url(#filter4_d_37_192)">
<circle cx="320" cy="645" r="25" fill="#A5D6A7"/> <circle cx="320" cy="645" r="25" fill="#9e9e9e"/>
<circle cx="320" cy="645" r="25" stroke="black" stroke-width="2"/> <circle cx="320" cy="645" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter5_d_37_192)"> <g filter="url(#filter5_d_37_192)">
<circle cx="295" cy="773" r="25" fill="#E57373"/> <circle cx="295" cy="773" r="25" fill="#9e9e9e"/>
<circle cx="295" cy="773" r="25" stroke="black" stroke-width="2"/> <circle cx="295" cy="773" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter6_d_37_192)"> <g filter="url(#filter6_d_37_192)">
<circle cx="239" cy="880" r="25" fill="#38809E"/> <circle cx="239" cy="880" r="25" fill="#9e9e9e"/>
<circle cx="239" cy="880" r="25" stroke="black" stroke-width="2"/> <circle cx="239" cy="880" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter7_d_37_192)"> <g filter="url(#filter7_d_37_192)">
<circle cx="354" cy="959" r="25" fill="#D9D9D9"/> <circle cx="354" cy="959" r="25" fill="#9e9e9e"/>
<circle cx="354" cy="959" r="25" stroke="black" stroke-width="2"/> <circle cx="354" cy="959" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter8_d_37_192)"> <g filter="url(#filter8_d_37_192)">
<circle cx="270" cy="1036" r="25" fill="#D9D9D9"/> <circle cx="270" cy="1036" r="25" fill="#9e9e9e"/>
<circle cx="270" cy="1036" r="25" stroke="black" stroke-width="2"/> <circle cx="270" cy="1036" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter9_d_37_192)"> <g filter="url(#filter9_d_37_192)">
<circle cx="279" cy="1174" r="25" fill="#D9D9D9"/> <circle cx="279" cy="1174" r="25" fill="#9e9e9e"/>
<circle cx="279" cy="1174" r="25" stroke="black" stroke-width="2"/> <circle cx="279" cy="1174" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter10_d_37_192)"> <g filter="url(#filter10_d_37_192)">
<circle cx="337" cy="1302" r="25" fill="#D9D9D9"/> <circle cx="337" cy="1302" r="25" fill="#9e9e9e"/>
<circle cx="337" cy="1302" r="25" stroke="black" stroke-width="2"/> <circle cx="337" cy="1302" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter11_d_37_192)"> <g filter="url(#filter11_d_37_192)">
<circle cx="250" cy="1388" r="25" fill="#D9D9D9"/> <circle cx="250" cy="1388" r="25" fill="#9e9e9e"/>
<circle cx="250" cy="1388" r="25" stroke="black" stroke-width="2"/> <circle cx="250" cy="1388" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter12_d_37_192)"> <g filter="url(#filter12_d_37_192)">
<circle cx="162" cy="1487" r="25" fill="#D9D9D9"/> <circle cx="162" cy="1487" r="25" fill="#9e9e9e"/>
<circle cx="162" cy="1487" r="25" stroke="black" stroke-width="2"/> <circle cx="162" cy="1487" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter13_d_37_192)"> <g filter="url(#filter13_d_37_192)">
<circle cx="306" cy="1531" r="25" fill="#D9D9D9"/> <circle cx="306" cy="1531" r="25" fill="#9e9e9e"/>
<circle cx="306" cy="1531" r="25" stroke="black" stroke-width="2"/> <circle cx="306" cy="1531" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter14_d_37_192)"> <g filter="url(#filter14_d_37_192)">
<circle cx="342" cy="1649" r="25" fill="#D9D9D9"/> <circle cx="342" cy="1649" r="25" fill="#9e9e9e"/>
<circle cx="342" cy="1649" r="25" stroke="black" stroke-width="2"/> <circle cx="342" cy="1649" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter15_d_37_192)"> <g filter="url(#filter15_d_37_192)">
<circle cx="225" cy="1724" r="25" fill="#D9D9D9"/> <circle cx="225" cy="1724" r="25" fill="#9e9e9e"/>
<circle cx="225" cy="1724" r="25" stroke="black" stroke-width="2"/> <circle cx="225" cy="1724" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter16_d_37_192)"> <g filter="url(#filter16_d_37_192)">
<circle cx="216" cy="1822" r="25" fill="#D9D9D9"/> <circle cx="216" cy="1822" r="25" fill="#9e9e9e"/>
<circle cx="216" cy="1822" r="25" stroke="black" stroke-width="2"/> <circle cx="216" cy="1822" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter17_d_37_192)"> <g filter="url(#filter17_d_37_192)">
<circle cx="275" cy="1883" r="25" fill="#D9D9D9"/> <circle cx="275" cy="1883" r="25" fill="#9e9e9e"/>
<circle cx="275" cy="1883" r="25" stroke="black" stroke-width="2"/> <circle cx="275" cy="1883" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter18_d_37_192)"> <g filter="url(#filter18_d_37_192)">
<circle cx="362" cy="1917" r="25" fill="#D9D9D9"/> <circle cx="362" cy="1917" r="25" fill="#9e9e9e"/>
<circle cx="362" cy="1917" r="25" stroke="black" stroke-width="2"/> <circle cx="362" cy="1917" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
<g filter="url(#filter19_d_37_192)"> <g filter="url(#filter19_d_37_192)">
<circle cx="300" cy="2037" r="25" fill="#D9D9D9"/> <circle cx="300" cy="2037" r="25" fill="#9e9e9e"/>
<circle cx="300" cy="2037" r="25" stroke="black" stroke-width="2"/> <circle cx="300" cy="2037" r="25" stroke="#757575" stroke-width="2"/>
</g> </g>
</g> </g>
<defs> <defs>

Before

Width:  |  Height:  |  Size: 493 KiB

After

Width:  |  Height:  |  Size: 493 KiB

+216
View File
@@ -0,0 +1,216 @@
/**
* Utility to dynamically populate the map SVG with clue points
* based on the total number of clues in the database
*/
/**
* Fetches the total number of clues from the API
* @returns {Promise<number>} The total number of clues
*/
async function fetchTotalClues() {
try {
const response = await fetch("/api/clues", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store, no-cache, must-revalidate",
},
credentials: "include",
});
if (!response.ok) {
throw new Error(`Failed to fetch clues: ${response.status}`);
}
const clues = await response.json();
return clues.length;
} catch (error) {
console.error("Error fetching total clues:", error);
return 0;
}
}
/**
* Shows the specified number of clue points on the map
* @param {SVGElement} svgElement - The SVG DOM element of the map
* @param {number} numClues - Number of clues to display
* @returns {boolean} Success status
*/
function showCluePoints(svgElement, numClues) {
if (!svgElement || !numClues) {
console.error("Invalid SVG element or number of clues");
return false;
}
try {
// Find all clue points in the SVG - improved selector for better compatibility
const cluePoints = Array.from(svgElement.querySelectorAll("circle")).filter(
(circle) =>
circle.classList.contains("clue-point") ||
circle.getAttribute("class")?.includes("clue-point")
);
console.log(`Found ${cluePoints.length} clue points in SVG`);
// If no clue points are found, add them programmatically
if (cluePoints.length === 0) {
console.log("No clue points found, creating them dynamically");
return createCluePoints(svgElement, numClues);
}
// Hide all clue points first
cluePoints.forEach((circle) => {
circle.style.display = "none";
});
// Show only the required number of clue points
for (let i = 0; i < Math.min(numClues, cluePoints.length); i++) {
const circle = cluePoints[i];
circle.style.display = "";
// Ensure the circle has the clue-point class and a data-clue-id
circle.classList.add("clue-point");
if (!circle.hasAttribute("data-clue-id")) {
circle.setAttribute("data-clue-id", (i + 1).toString());
}
}
console.log(
`Showing ${Math.min(numClues, cluePoints.length)} clue points on map`
);
return true;
} catch (error) {
console.error("Error showing clue points:", error);
return false;
}
}
/**
* Creates clue points dynamically if they don't exist in the SVG
* @param {SVGElement} svgElement - The SVG DOM element of the map
* @param {number} numClues - Number of clues to create
* @returns {boolean} Success status
*/
function createCluePoints(svgElement, numClues) {
try {
const svgWidth = svgElement.viewBox.baseVal.width || 800;
const svgHeight = svgElement.viewBox.baseVal.height || 600;
// Define positions for clue points - spread across the map
const positions = [];
// Calculate positions in a grid pattern
const cols = Math.ceil(Math.sqrt(numClues));
const rows = Math.ceil(numClues / cols);
const marginX = svgWidth * 0.1;
const marginY = svgHeight * 0.1;
const spacingX = (svgWidth - 2 * marginX) / (cols - 1 || 1);
const spacingY = (svgHeight - 2 * marginY) / (rows - 1 || 1);
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const index = row * cols + col;
if (index < numClues) {
positions.push({
x: marginX + col * spacingX,
y: marginY + row * spacingY,
});
}
}
}
// Create circles for each clue
positions.forEach((pos, index) => {
const circle = document.createElementNS(
"http://www.w3.org/2000/svg",
"circle"
);
circle.setAttribute("cx", pos.x);
circle.setAttribute("cy", pos.y);
circle.setAttribute("r", 10);
circle.setAttribute("fill", "#9e9e9e");
circle.setAttribute("stroke", "#757575");
circle.setAttribute("stroke-width", "2");
circle.setAttribute("class", "clue-point");
circle.setAttribute("data-clue-id", (index + 1).toString());
svgElement.appendChild(circle);
});
console.log(`Created ${numClues} clue points dynamically`);
return true;
} catch (error) {
console.error("Error creating clue points:", error);
return false;
}
}
/**
* Main function to populate map with the correct number of clue points
* @param {SVGElement} svgElement - The SVG DOM element of the map
* @returns {Promise<boolean>} Success status
*/
export async function populateMap(svgElement) {
if (!svgElement) {
console.error("No SVG element provided");
return false;
}
try {
console.log("Starting to populate map");
// Fetch total number of clues
const totalClues = await fetchTotalClues();
console.log("Total clues fetched:", totalClues);
if (totalClues > 0) {
// Show the appropriate number of clue points
return showCluePoints(svgElement, totalClues);
} else {
console.warn("No clues found in database");
return false;
}
} catch (error) {
console.error("Error populating map:", error);
return false;
}
}
/**
* Updates the styling of clue points based on their status
* @param {SVGElement} svgElement - The SVG DOM element of the map
* @param {Array} clues - Array of clue objects with status information
*/
export function updateCluePointStatus(svgElement, clues) {
if (!svgElement || !clues || !clues.length) {
console.error("Invalid SVG element or clues data");
return;
}
try {
clues.forEach((clue, index) => {
// Find the corresponding circle in the SVG
const circle = svgElement.querySelector(
`.clue-point[data-clue-id="${clue.id}"]`
);
if (circle) {
// Apply appropriate styling based on clue status
if (clue.found) {
// Found clues are green
circle.style.fill = "#4caf50";
circle.style.stroke = "#2e7d32";
} else if (clue.available) {
// Available clues are orange
circle.style.fill = "#ff9800";
circle.style.stroke = "#d87f00";
} else {
// Unavailable clues remain grey
circle.style.fill = "#9e9e9e";
circle.style.stroke = "#757575";
}
}
});
} catch (error) {
console.error("Error updating clue point status:", error);
}
}