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
+645 -310

No files matched your search

+287 -246
View File
@@ -10,6 +10,7 @@ import {
clearHuntTimer,
formatElapsedTime,
} from "@/utils/timerService";
import { populateMap, updateCluePointStatus } from "@/utils/map-populate";
export default function MapPage() {
const { data: session, status } = useSession();
@@ -39,300 +40,217 @@ export default function MapPage() {
// Hard redirect function (for when a full page reload is needed)
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
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
// Fetch team data for the current user
const fetchTeamData = useCallback(async () => {
if (!isMounted.current) return;
try {
setLoading(true);
setError(null);
const response = await fetch("/api/user/team", {
method: "GET",
headers: {
"Content-Type": "application/json",
"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",
});
if (!response.ok) {
// Handle specific error cases without immediate redirect
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");
}
throw new Error("Failed to fetch clues");
}
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
const fetchClues = useCallback(async () => {
try {
const response = await fetch("/api/clues", {
headers: { "Cache-Control": "no-cache, no-store, must-revalidate" },
credentials: "include",
// Process the clues to determine which are available
// A clue is available if it's either found already or the next in sequence
const processedClues = data.map((clue, index, arr) => {
// Find the first unfound clue's index
const firstUnfoundIndex = arr.findIndex((c) => !c.found);
// 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) {
const cluesData = await response.json();
setClues(cluesData);
}
} catch (error) {
console.error("Failed to fetch clues:", error);
setClues(processedClues);
return processedClues;
} catch (err) {
console.error("Failed to fetch clues:", err);
setError(err.message);
return [];
}
}, []);
// Function to load and enhance the SVG map
const loadAndEnhanceMap = useCallback(async () => {
try {
// Fetch the SVG file
const response = await fetch("/images/map.svg");
if (!response.ok) {
console.error(
"Failed to load SVG:",
response.status,
response.statusText
);
setMapError(true);
return;
}
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) {
console.error("Failed to load map SVG:", error);
setMapError(true);
setLoading(false);
}
}, []);
// Function to enhance SVG with clickable areas
// Enhanced function to populate the map with clue points
const enhanceSvgMap = useCallback(() => {
if (!mapContainerRef.current || !clues.length) return;
if (!mapContainerRef.current) return;
// Find all circles in the SVG
const circleSvgElements =
mapContainerRef.current.querySelectorAll("circle");
console.log(`Found ${circleSvgElements.length} circles in SVG`);
// 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;
// Find the SVG element inside the map container
const svgElement = mapContainerRef.current.querySelector("svg");
if (!svgElement) {
console.error("No SVG element found in map container");
return;
}
// Convert NodeList to Array for easier manipulation
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];
console.log("SVG element found, starting enhancement");
// Check if this clue is available (either found or next in sequence)
const isAvailable = clue.found || index <= nextAvailableClueIndex;
// Use our utility to populate the map with clue points
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);
// Make circle interactive
circle.style.cursor = isAvailable ? "pointer" : "not-allowed";
// 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;
// Set appropriate colors
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";
// Make circle interactive
circle.style.cursor = isAvailable ? "pointer" : "not-allowed";
// Add click handler
circle.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
if (isAvailable) {
console.log(`Navigating to clue ${clue.id}`);
router.push(`/clue/${clue.id}`);
} else {
alert("Complete previous clues first to unlock this one!");
}
};
// Add hover effects
circle.onmouseenter = () => {
if (isAvailable) {
circle.style.fill = "#ffb74d"; // Lighter orange for hover
}
};
circle.onmouseleave = () => {
if (clue.found) {
circle.style.fill = "#4caf50"; // Back to green for found clues
} else if (isAvailable) {
circle.style.fill = "#ff9800"; // Back to orange for available clues
} else {
circle.style.fill = "#9e9e9e"; // Back to grey for unavailable clues
}
};
// Add tooltip with clue information
const label = document.createElementNS(
"http://www.w3.org/2000/svg",
"title"
);
label.textContent = `Clue #${index + 1}: ${
clue.title || "Mystery clue"
}${!isAvailable ? " (Locked)" : ""}`;
circle.appendChild(label);
}
});
} else {
// Unavailable clues are grey
circle.style.fill = "#9e9e9e";
circle.style.stroke = "#757575";
console.error("Failed to populate map");
}
circle.style.strokeWidth = "2";
// Add click handler to navigate to the clue page, but only if available
circle.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
if (isAvailable) {
console.log(`Navigating to clue ${clue.id}`);
router.push(`/clue/${clue.id}`);
} else {
alert("Complete previous clues first to unlock this one!");
}
};
// Add hover effects
circle.onmouseenter = () => {
if (isAvailable) {
circle.style.fill = "#ffb74d"; // Lighter orange for hover
}
};
circle.onmouseleave = () => {
if (clue.found) {
circle.style.fill = "#4caf50"; // Back to green for found clues
} else if (isAvailable) {
circle.style.fill = "#ff9800"; // Back to orange for available clues
} else {
circle.style.fill = "#9e9e9e"; // Back to grey for unavailable clues
}
};
// Add tooltip/title with actual clue ID and position information
const label = document.createElementNS(
"http://www.w3.org/2000/svg",
"title"
);
label.textContent = `Clue #${index + 1}: ${
clue.title || "Mystery clue"
}${!isAvailable ? " (Locked)" : ""}`;
circle.appendChild(label);
}
});
})
.catch((error) => {
console.error("Error enhancing SVG map:", error);
setMapError(true);
});
}, [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
async function checkHuntAndTimer() {
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
useEffect(() => {
// Initialize the timer without waiting for teamData
@@ -533,6 +522,57 @@ export default function MapPage() {
return () => clearInterval(intervalId);
}, [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) {
return (
<div className={styles["loading-container"]}>
@@ -588,13 +628,14 @@ export default function MapPage() {
<div className={styles["team-code"]}>{teamData?.team?.code || ""}</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["treasure-map"]}>
{mapSvg ? (
<div
className={styles["svg-container"]}
dangerouslySetInnerHTML={{ __html: mapSvg }}
onLoad={() => console.log("SVG container loaded")}
/>
) : (
<div
@@ -606,7 +647,7 @@ export default function MapPage() {
</div>
</div>
{/* Navigation bar at the bottom */}
{/* Navigation bar */}
<nav className={styles["nav-bar"]}>
<Link
href="/map"