This commit is contained in:
Sebastien Riviere
2025-08-27 00:08:16 +02:00
18 changed files with 495 additions and 85 deletions

View File

@@ -0,0 +1,268 @@
"use client";
import { useLocation } from "@/hook/useLocation";
import { useEffect, useState, useRef, useCallback } from "react";
import "leaflet/dist/leaflet.css";
import { Circle, MapContainer, Marker, TileLayer, useMap, Tooltip, Polyline } from "react-leaflet";
import { useMapCircleDraw } from "@/hook/mapDrawing";
import useAdmin from "@/hook/useAdmin";
import { GameState } from "@/util/gameState";
import L from "leaflet";
import { createPortal } from "react-dom";
import TeamInformation from "@/components/admin/teamInformation";
function MapActionControl({ onClick, children }) {
const map = useMap();
useEffect(() => {
const controlDiv = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');
controlDiv.style.background = 'rgba(0,0,0,0.25)';
controlDiv.style.borderRadius = '9999px';
controlDiv.style.padding = '8px';
controlDiv.style.border = 'none';
controlDiv.title = "Plein écran";
controlDiv.style.display = "flex";
controlDiv.style.alignItems = "center";
controlDiv.style.justifyContent = "center";
controlDiv.style.width = "56px";
controlDiv.style.height = "56px";
controlDiv.onclick = onClick;
controlDiv.innerHTML = `<img src="./icons/fullscreen.png" alt="" style="width:36px;height:36px;" />`;
const customControl = L.control({ position: 'bottomleft' });
customControl.onAdd = () => controlDiv;
customControl.addTo(map);
return () => {
customControl.remove();
};
}, [map, onClick, children]);
return null;
}
function LeafletSidePanel({ show, onClose, children }) {
const map = useMap();
const panelRef = useRef(document.createElement("div"));
useEffect(() => {
const panelDiv = panelRef.current;
panelDiv.className = "leaflet-control leaflet-control-custom";
const control = L.control({ position: "topright" });
control.onAdd = () => panelDiv;
if (show) control.addTo(map);
return () => {
control.remove();
};
}, [map, show]);
if (!show) return null;
return createPortal(
<>
<button
style={{
position: "absolute",
top: "1rem",
right: "1rem",
fontSize: "3rem",
background: "none",
border: "none",
cursor: "pointer",
color: "#888"
}}
onClick={onClose}
title="Fermer"
>
×
</button>
{children}
</>,
panelRef.current
);
}
const positionIcon = new L.Icon({
iconUrl: '/icons/location.png',
iconSize: [30, 30],
iconAnchor: [15, 15],
popupAnchor: [0, -15],
shadowSize: [30, 30],
});
function MapPan(props) {
const map = useMap();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!initialized && props.center) {
map.flyTo(props.center, props.zoom, { animate: false });
setInitialized(true)
}
}, [props.center]);
return null;
}
function MapEventListener({ onClick, onMouseMove }) {
const map = useMap();
useEffect(() => {
map.on('click', onClick);
return () => {
map.off('click', onClick);
}
}, [onClick]);
useEffect(() => {
map.on('mousemove', onMouseMove);
return () => {
map.off('mousemove', onMouseMove);
}
});
return null;
}
const DEFAULT_ZOOM = 14;
export function CircularAreaPicker({ area, setArea, markerPosition, ...props }) {
const location = useLocation(Infinity);
const { handleClick, handleMouseMove, center, radius } = useMapCircleDraw(area, setArea);
return (
<MapContainer {...props} className='min-h-full w-full ' center={location} zoom={DEFAULT_ZOOM} scrollWheelZoom={true}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{center && radius && <Circle center={center} radius={radius} fillColor="blue" />}
{markerPosition && <Marker position={markerPosition} icon={positionIcon}>
</Marker>}
<MapPan center={location} zoom={DEFAULT_ZOOM} />
<MapEventListener onClick={handleClick} onMouseMove={handleMouseMove} />
</MapContainer>)
}
export const EditMode = {
MIN: 0,
MAX: 1
}
export function ZonePicker({ minZone, setMinZone, maxZone, setMaxZone, editMode, ...props }) {
const location = useLocation(Infinity);
const { handleClick: maxClick, handleMouseMove: maxHover, center: maxCenter, radius: maxRadius } = useMapCircleDraw(minZone, setMinZone);
const { handleClick: minClick, handleMouseMove: minHover, center: minCenter, radius: minRadius } = useMapCircleDraw(maxZone, setMaxZone);
function handleClick(e) {
if (editMode == EditMode.MAX) {
maxClick(e);
} else {
minClick(e);
}
}
function handleMouseMove(e) {
if (editMode == EditMode.MAX) {
maxHover(e);
} else {
minHover(e);
}
}
return (
<div>
<div className='h-96'>
<MapContainer {...props} className='min-h-full w-full ' center={location} zoom={DEFAULT_ZOOM} scrollWheelZoom={true}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{minCenter && minRadius && <Circle center={minCenter} radius={minRadius} color="blue" fillColor="blue" />}
{maxCenter && maxRadius && <Circle center={maxCenter} radius={maxRadius} color="red" fillColor="red" />}
<MapPan center={location} zoom={DEFAULT_ZOOM} />
<MapEventListener onClick={handleClick} onMouseMove={handleMouseMove} />
</MapContainer>
</div>
{ maxCenter && minCenter && typeof maxCenter.distanceTo === 'function'
&& maxRadius + maxCenter.distanceTo(minCenter) >= minRadius
&& <p className="text-red-500">La zone de fin doit être incluse dans celle de départ</p>}
</div>
)
}
export function LiveMap({ selectedTeamId, setSelectedTeamId }) {
const location = useLocation(Infinity);
const [timeLeftNextZone, setTimeLeftNextZone] = useState(null);
const { zone, zoneExtremities, teams, nextZoneDate, isShrinking , getTeam, gameState } = useAdmin();
function handleMarkerClick(teamId) {
setSelectedTeamId(teamId);
}
const mapWrapperRef = useRef(null);
const handleFullscreen = useCallback(() => {
const el = mapWrapperRef.current;
if (!el) return;
if (!document.fullscreenElement) {
el.requestFullscreen();
} else {
document.exitFullscreen();
}
}, []);
// Remaining time before sending position
useEffect(() => {
const updateTime = () => {
setTimeLeftNextZone(Math.max(0, Math.floor((nextZoneDate - Date.now()) / 1000)));
};
updateTime();
const interval = setInterval(updateTime, 1000);
return () => clearInterval(interval);
}, [nextZoneDate]);
function formatTime(time) {
// time is in seconds
if (time < 0) return "00:00";
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
return String(minutes).padStart(2,"0") + ":" + String(seconds).padStart(2,"0");
}
function Arrow({pos1, pos2}) {
if (pos1 && pos2) {
return (
<Polyline positions={[pos1, pos2]} pathOptions={{ color: 'black', weight: 3 }}/>
)
} else {
return null;
}
}
return (
<div className='h-full w-full' ref ={mapWrapperRef}>
{gameState == GameState.PLAYING && <p>{`${isShrinking ? "Fin" : "Début"} du rétrécissement de la zone dans : ${formatTime(timeLeftNextZone)}`}</p>}
<MapContainer className='min-h-full w-full' center={location} zoom={DEFAULT_ZOOM} scrollWheelZoom={true}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapPan center={location} zoom={DEFAULT_ZOOM} />
{gameState == GameState.PLAYING && zone && <Circle center={zone.center} radius={zone.radius} color="blue" />}
{gameState == GameState.PLAYING && zoneExtremities && <Circle center={zoneExtremities.begin.center} radius={zoneExtremities.begin.radius} color='black' fill={false} />}
{gameState == GameState.PLAYING && zoneExtremities && <Circle center={zoneExtremities.end.center} radius={zoneExtremities.end.radius} color='red' fill={false} />}
{teams.map((team) => team.currentLocation && !team.captured &&
<Marker key={team.id} position={team.currentLocation} icon={positionIcon}>
<Tooltip permanent direction="top" offset={[0, -5]} className="custom-tooltip">{team.name}</Tooltip>
<Arrow pos1={team.currentLocation} pos2={getTeam(team.chasing).currentLocation}/>
</Marker>
)}
<MapActionControl onClick={handleFullscreen}/>
{selectedTeamId && (
<LeafletSidePanel show={true} onClose={() => setSelectedTeamId(null)}>
<TeamInformation
selectedTeamId={selectedTeamId}
onClose={() => setSelectedTeamId(null)}
/>
</LeafletSidePanel>
)}
</MapContainer>
</div>
)
}

View File

@@ -1,6 +1,4 @@
import { useState } from 'react'
import { TextInput } from '../util/textInput'
import { BlueButton } from '../util/button'
export default function TeamAddForm({onAddTeam}) {
const [teamName, setTeamName] = useState('');
@@ -14,12 +12,12 @@ export default function TeamAddForm({onAddTeam}) {
}
return (
<form className='flex flex-row m-y-5' onSubmit={handleSubmit}>
<form className='flex flex-row m-y-5 mb-3' onSubmit={handleSubmit}>
<div className='w-4/5'>
<TextInput name="teamName" label='Team name' value={teamName} onChange={(e) => setTeamName(e.target.value)}/>
<input name="teamName" label='Team name' value={teamName} onChange={(e) => setTeamName(e.target.value)} type="text" className="block w-full h-full p-4 text-center ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-400" />
</div>
<div className='w-1/5'>
<BlueButton type="submit" className="w-5">+</BlueButton>
<button type="submit" className="w-5 w-full h-full bg-custom-light-blue hover:bg-blue-500 transition text-3xl font-bold">+</button>
</div>
</form>
);

View File

@@ -0,0 +1,75 @@
import useAdmin from "@/hook/useAdmin";
function DotLine({ label, value }) {
return (
<div className="flex items-center">
<span className="text-lg">{label}</span>
<span
className="flex-1 mx-2 overflow-hidden whitespace-nowrap text-black font-bold select-none"
aria-hidden="true"
>
{" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "}
</span>
<span className="text-lg">{value}</span>
</div>
);
}
// ...existing imports...
export default function TeamInformation({ selectedTeamId, onClose }) {
const { getTeam, getTeamName, teams } = useAdmin();
const team = getTeam(selectedTeamId);
if (!team) return null;
function formatTime(seconds) {
if (!seconds || seconds < 0) return "—";
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);
return `${m}:${s.toString().padStart(2, "0")}`;
}
// Determine image source
const imageSrc = team.photoUrl && team.photoUrl.trim() !== ""
? team.photoUrl
: "/images/missing_image.jpg";
return (
<div className="bg-white p-6 w-[20rem] max-w-full relative">
<button
className="absolute top-2 right-2 text-black text-6xl mr-3"
onClick={onClose}
title="Fermer"
>
×
</button>
<div className={`text-2xl font-bold text-center mb-2 ${team.captured ? "text-custom-red" : "text-custom-green"} font-bold`}>
{team.captured ? "Capturée" : "En jeu"}
</div>
<div className="text-4xl font-bold text-center mb-4">
{team.name}
</div>
<div className="mb-4 flex justify-center">
<img
src={imageSrc}
alt=""
className=""
/>
</div>
<DotLine label="ID de capture" value={String(team.captureCode).padStart(4, '0')} />
<DotLine label="ID d'équipe" value={String(team.id).padStart(6, '0')} />
<div className="h-4" />
<DotLine label="Chasse" value={getTeamName(team.chasing) ?? "—"} />
<DotLine label="Chassé par" value={getTeamName(team.chased) ?? "—"} />
<div className="h-6" />
<DotLine label="Distance" value={team.distanceTravelled != null ? `${team.distanceTravelled.toFixed(2)} m` : "—"} />
<DotLine label="Temps de survie" value={team.timeAlive != null ? formatTime(team.timeAlive) : "—"} />
<DotLine label="Vitesse moyenne" value={team.averageSpeed != null ? `${team.averageSpeed.toFixed(2)} m/s` : "—"} />
<DotLine label="Captures" value={team.nCaptures ?? "—"} />
<DotLine label="Observations" value={team.nObservations ?? "—"} />
<DotLine label="Observé" value={team.nObserved ?? "—"} />
<DotLine label="Hors zone" value={team.outOfZone ? "Vrai" : "Faux" ?? "—"} />
</div>
);
}

View File

@@ -1,6 +1,8 @@
import useAdmin from '@/hook/useAdmin';
import { GameState } from '@/util/gameState';
import { DragDropContext, Draggable, Droppable } from '@hello-pangea/dnd';
import React from 'react'
import { useFormStatus } from 'react-dom';
function reorder(list, startIndex, endIndex) {
const result = Array.from(list);
@@ -9,15 +11,33 @@ function reorder(list, startIndex, endIndex) {
return result;
};
function TeamListItem({ team, index, onSelected, itemSelected }) {
const bgColor = team.captured ? " bg-red-400" : " bg-gray-300";
const border = " border border-4 " + (itemSelected ? "border-black" : team.captured ? "border-red-400" : "border-gray-300");
const classNames = 'w-full p-3 my-3' + (bgColor) + (border);
const TEAM_STATUS = {
playing: { label: "En jeu", color: "text-custom-green" },
captured: { label: "Capturée", color: "text-custom-red" },
outofzone: { label: "Hors zone", color: "text-custom-orange" },
ready: { label: "Prête", color: "text-custom-blue" },
notready: { label: "En préparation", color: "text-custom-grey" },
};
function TeamListItem({ team, index, onSelected, itemSelected, gamestate }) {
console.log(gamestate === GameState.PLAYING ? "En jeu" : "En préparation");
const status = gamestate === GameState.PLAYING ? (team.captured ? TEAM_STATUS.captured : (team.outofzone ? TEAM_STATUS.outofzone : TEAM_STATUS.playing)) : (team.ready ? TEAM_STATUS.ready : TEAM_STATUS.notready);
return (
<Draggable draggableId={team.id.toString()} index={index} onClick={() => onSelected(team.id)}>
{provided => (
<div className={classNames} {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef}>
<p className='text-center'>{team.name}</p>
<div className='w-full p-2 bg-white border-2 border-gray-300 flex flex-row items-center text-3xl gap-3 font-bold' {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef}>
<div className="w-12 h-12 grid grid-cols-2 grid-rows-2 gap-1">
<img src="/icons/greendude.png" className="w-6 h-6 object-contain" />
<img src="/icons/greenlocation.png" className="w-6 h-6 object-contain" />
<img src="/icons/greenconnection.png" className="w-6 h-6 object-contain" />
<img src="/icons/greenbattery.png" className="w-6 h-6 object-contain" />
</div>
<div className='flex-1 w-full h-full flex flex-row items-center justify-between'>
<p className='text-center'>{team.name}</p>
<p className={`text-center ${status.color}`}>
{status.label}
</p>
</div>
</div>
)}
@@ -26,8 +46,7 @@ function TeamListItem({ team, index, onSelected, itemSelected }) {
}
export default function TeamList({selectedTeamId, onSelected}) {
const {teams, reorderTeams} = useAdmin();
const {teams, reorderTeams, gameState} = useAdmin();
function onDragEnd(result) {
if (!result.destination) return;
if (result.destination.index === result.source.index) return;
@@ -42,7 +61,7 @@ export default function TeamList({selectedTeamId, onSelected}) {
<ul ref={provided.innerRef} {...provided.droppableProps}>
{teams.map((team, i) => (
<li key={team.id} onClick={() => onSelected(team.id)}>
<TeamListItem onSelected={onSelected} index={i} itemSelected={selectedTeamId === team.id} team={team} />
<TeamListItem onSelected={onSelected} index={i} itemSelected={selectedTeamId === team.id} team={team} gamestate={gameState} />
</li>
))}
{provided.placeholder}