Réorganisation des dossiers

This commit is contained in:
Sebastien Riviere
2025-08-28 00:06:14 +02:00
parent 4a8d005f44
commit cb534ed1aa
31 changed files with 134 additions and 677 deletions

View File

@@ -1,118 +0,0 @@
import { useEffect, useState } from "react";
import { BlueButton, GreenButton, RedButton } from "../util/button";
import { TextInput } from "../util/textInput";
import useAdmin from "@/hook/useAdmin";
import useLocation from "@/hook/useLocation";
import "leaflet/dist/leaflet.css";
import { Circle, MapContainer, TileLayer } from "react-leaflet";
import useMapCircleDraw from "@/hook/useMapCircleDraw";
import { MapPan, MapEventListener } from "./mapUtils";
const DEFAULT_ZOOM = 14;
const EditMode = {
MIN: 0,
MAX: 1
}
function CircleDrawings({ minZone, setMinZone, maxZone, setMaxZone, editMode }) {
const { center: maxCenter, radius: maxRadius, handleLeftClick: maxLeftClick, handleRightClick: maxRightClick, handleMouseMove: maxHover } = useMapCircleDraw(maxZone, setMaxZone);
const { center: minCenter, radius: minRadius, handleLeftClick: minLeftClick, handleRightClick: minRightClick, handleMouseMove: minHover } = useMapCircleDraw(minZone, setMinZone);
function handleLeftClick(e) {
if (editMode == EditMode.MAX) {
maxLeftClick(e);
} else {
minLeftClick(e);
}
}
function handleRightClick(e) {
if (editMode == EditMode.MAX) {
maxRightClick(e);
} else {
minRightClick(e);
}
}
function handleMouseMove(e) {
if (editMode == EditMode.MAX) {
maxHover(e);
} else {
minHover(e);
}
}
return (
<div>
{minCenter && minRadius && <Circle center={minCenter} radius={minRadius} color="blue" fillColor="blue" />}
{maxCenter && maxRadius && <Circle center={maxCenter} radius={maxRadius} color="red" fillColor="red" />}
<MapEventListener onLeftClick={handleLeftClick} onRightClick={handleRightClick} onMouseMove={handleMouseMove} />
</div>
);
}
export function CircleZonePicker({ minZone, maxZone, editMode, setMinZone, setMaxZone, ...props }) {
const location = useLocation(Infinity);
return (
<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"
/>
<MapPan center={location} zoom={DEFAULT_ZOOM} />
<CircleDrawings minZone={minZone} maxZone={maxZone} editMode={editMode} setMinZone={setMinZone} setMaxZone={setMaxZone} />
</MapContainer>
</div>
);
}
export default function CircleZoneMap() {
const [editMode, setEditMode] = useState(EditMode.MIN);
const [minZone, setMinZone] = useState(null);
const [maxZone, setMaxZone] = useState(null);
const [reductionCount, setReductionCount] = useState("");
const [duration, setDuration] = useState("");
const {zoneSettings, changeZoneSettings} = useAdmin();
useEffect(() => {
if (zoneSettings) {
setMinZone(zoneSettings.min);
setMaxZone(zoneSettings.max);
setReductionCount(zoneSettings.reductionCount.toString());
setDuration(zoneSettings.duration.toString());
}
}, [zoneSettings]);
function handleSettingsSubmit() {
const newSettings = {min:minZone, max:maxZone, reductionCount: Number(reductionCount), duration: Number(duration)};
changeZoneSettings(newSettings);
}
// When the user set one zone, switch to the other
useEffect(() => {
if(editMode == EditMode.MIN) {
setEditMode(EditMode.MAX);
}else {
setEditMode(EditMode.MIN);
}
}, [minZone, maxZone]);
return <div className='w-2/5 h-full gap-1 bg-white p-10 flex flex-col text-center shadow-2xl overflow-y-scroll'>
<h2 className="text-2xl">Edit zones</h2>
{editMode == EditMode.MIN && <BlueButton onClick={() => setEditMode(EditMode.MAX)}>Click to edit first zone</BlueButton>}
{editMode == EditMode.MAX && <RedButton onClick={() => setEditMode(EditMode.MIN)}>Click to edit last zone</RedButton>}
<CircleZonePicker minZone={minZone} maxZone={maxZone} editMode={editMode} setMinZone={setMinZone} setMaxZone={setMaxZone} />
<div>
<p>Number of zones</p>
<TextInput value={reductionCount} onChange={(e) => setReductionCount(e.target.value)}></TextInput>
</div>
<div>
<p>Duration of a zone</p>
<TextInput value={duration} onChange={(e) => setDuration(e.target.value)}></TextInput>
</div>
<GreenButton onClick={handleSettingsSubmit}>Apply</GreenButton>
</div>
}

View File

@@ -1,48 +0,0 @@
import useAdmin from "@/hook/useAdmin";
import { GreenButton } from "../util/button";
import { Section } from "../util/section";
import { useEffect, useState } from "react";
function MessageInput({title, ...props}) {
return (
<div className="w-full flex flex-row gap-3 items-center">
<p>{title}</p>
<input {...props} type="text" className="w-full h-8 p-2 rounded ring-1 ring-inset ring-gray-400 placeholder:text-gray-600" />
</div>
);
}
export default function GameSettings() {
const {gameSettings, changeGameSettings} = useAdmin();
const [capturedMessage, setCapturedMessage] = useState("");
const [winnerEndMessage, setWinnerEndMessage] = useState("");
const [loserEndMessage, setLoserEndMessage] = useState("");
const [waitingMessage, setWaitingMessage] = useState("");
useEffect(() => {
if (gameSettings) {
setCapturedMessage(gameSettings.capturedMessage);
setWinnerEndMessage(gameSettings.winnerEndGameMessage);
setLoserEndMessage(gameSettings.loserEndGameMessage);
setWaitingMessage(gameSettings.waitingMessage);
}
}, [gameSettings]);
function applySettings() {
changeGameSettings({capturedMessage: capturedMessage, winnerEndGameMessage: winnerEndMessage, loserEndGameMessage: loserEndMessage, waitingMessage: waitingMessage});
}
return (
<Section title="Message">
<div className="w-full h-full flex flex-col gap-3 items-center">
<MessageInput title="Attente  :" value={waitingMessage} onChange={(e) => setWaitingMessage(e.target.value)}/>
<MessageInput title="Capture :" value={capturedMessage} onChange={(e) => setCapturedMessage(e.target.value)} />
<MessageInput title="Victoire :" value={winnerEndMessage} onChange={(e) => setWinnerEndMessage(e.target.value)} />
<MessageInput title="Défaite  :" value={loserEndMessage} onChange={(e) => setLoserEndMessage(e.target.value)} />
<div className='w-40 h-15'>
<GreenButton onClick={applySettings}>Apply</GreenButton>
</div>
</div>
</Section>
);
}

View File

@@ -1,75 +0,0 @@
import useLocation from "@/hook/useLocation";
import { useEffect, useState } from "react";
import "leaflet/dist/leaflet.css";
import { MapContainer, Marker, TileLayer, Tooltip, Polyline, Polygon } from "react-leaflet";
import useAdmin from "@/hook/useAdmin";
import { GameState } from "@/util/gameState";
import { MapPan } from "./mapUtils";
const DEFAULT_ZOOM = 14;
const positionIcon = new L.Icon({
iconUrl: '/icons/location.png',
iconSize: [30, 30],
iconAnchor: [15, 15],
popupAnchor: [0, -15],
shadowSize: [30, 30],
});
export default function LiveMap() {
const location = useLocation(Infinity);
const [timeLeftNextZone, setTimeLeftNextZone] = useState(null);
const { zoneExtremities, teams, nextZoneDate, getTeam, gameState } = useAdmin();
// Remaining time before sending position
useEffect(() => {
if (nextZoneDate) {
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'>
{gameState == GameState.PLAYING && <p>{`Next zone in : ${formatTime(timeLeftNextZone)}`}</p>}
<MapContainer className='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 && zoneExtremities.begin && <Polygon positions={zoneExtremities.begin.points} pathOptions={{ color: 'red', fillColor: 'red', fillOpacity: '0.1', weight: 3 }} />}
{gameState == GameState.PLAYING && zoneExtremities.end && <Polygon positions={zoneExtremities.end.points} pathOptions={{ color: 'green', fillColor: 'green', fillOpacity: '0.1', weight: 3 }} />}
{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>
)}
</MapContainer>
</div>
)
}

View File

@@ -1,268 +0,0 @@
"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,32 +0,0 @@
import useLocation from "@/hook/useLocation";
import "leaflet/dist/leaflet.css";
import { Circle, MapContainer, Marker, TileLayer } from "react-leaflet";
import useMapCircleDraw from "@/hook/useMapCircleDraw";
import { MapPan, MapEventListener } from "./mapUtils";
const DEFAULT_ZOOM = 14;
const positionIcon = new L.Icon({
iconUrl: '/icons/location.png',
iconSize: [30, 30],
iconAnchor: [15, 15],
popupAnchor: [0, -15],
shadowSize: [30, 30],
});
export default function CircularAreaPicker({ area, setArea, markerPosition, ...props }) {
const location = useLocation(Infinity);
const { center, radius, handleLeftClick, handleRightClick, handleMouseMove } = 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} />}
<MapPan center={location} zoom={DEFAULT_ZOOM} />
<MapEventListener onLeftClick={handleLeftClick} onRightClick={handleRightClick} onMouseMove={handleMouseMove} />
</MapContainer>
);
}

View File

@@ -1,164 +0,0 @@
import { useEffect, useState } from "react";
import { GreenButton } from "../util/button";
import { TextInput } from "../util/textInput";
import useAdmin from "@/hook/useAdmin";
import useLocation from "@/hook/useLocation";
import "leaflet/dist/leaflet.css";
import { MapContainer, TileLayer, Polyline, Polygon, CircleMarker } from "react-leaflet";
import useMapPolygonDraw from "@/hook/useMapPolygonDraw";
import { MapPan, MapEventListener } from "./mapUtils";
const DEFAULT_ZOOM = 14;
function PolygonDrawings({ polygons, addPolygon, removePolygon }) {
const { currentPolygon, highlightNodes, handleLeftClick, handleRightClick, handleMouseMove } = useMapPolygonDraw(polygons, addPolygon, removePolygon);
const nodeSize = 5; // px
const lineThickness = 3; // px
function DrawNode({pos, color}) {
return (
<CircleMarker center={pos} radius={nodeSize} pathOptions={{ color: color, fillColor: color, fillOpacity: 1 }} />
);
}
function DrawLine({pos1, pos2, color}) {
return (
<Polyline positions={[pos1, pos2]} pathOptions={{ color: color, weight: lineThickness }} />
);
}
function DrawUnfinishedPolygon({polygon}) {
const length = polygon.length;
if (length > 0) {
return (
<div>
<DrawNode pos={polygon[0]} color={"red"} zIndexOffset={1000} />
{polygon.map((_, i) => {
if (i < length-1) {
return <DrawLine key={i} pos1={polygon[i]} pos2={polygon[i+1]} color={"red"} />;
} else {
return null;
}
})}
</div>
);
}
}
function DrawPolygon({polygon}) {
const length = polygon.length;
if (length > 2) {
return (
<Polygon positions={polygon} pathOptions={{ color: 'black', fillColor: 'black', fillOpacity: '0.5', weight: lineThickness }} />
);
}
}
return (
<div>
<MapEventListener onLeftClick={handleLeftClick} onRightClick={handleRightClick} onMouseMove={handleMouseMove} />
{polygons.map((polygon, i) => <DrawPolygon key={i} polygon={polygon} />)}
<DrawUnfinishedPolygon polygon={currentPolygon} />
{highlightNodes.map((node, i) => <DrawNode key={i} pos={node} color={"black"} />)}
</div>
);
}
function PolygonZonePicker({ polygons, addPolygon, removePolygon, ...props }) {
const location = useLocation(Infinity);
return (
<div className='h-full'>
<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"
/>
<MapPan center={location} zoom={DEFAULT_ZOOM} />
<PolygonDrawings polygons={polygons} addPolygon={addPolygon} removePolygon={removePolygon} />
</MapContainer>
</div>
);
}
export default function PolygonZoneMap() {
const defaultDuration = 10;
const [polygons, setPolygons] = useState([]);
const [durations, setDurations] = useState([]);
const {zoneSettings, changeZoneSettings} = useAdmin();
const {penaltySettings, changePenaltySettings} = useAdmin();
const [allowedTimeOutOfZone, setAllowedTimeOutOfZone] = useState("");
useEffect(() => {
if (zoneSettings) {
setPolygons(zoneSettings.polygons);
setDurations(zoneSettings.durations);
}
if (penaltySettings) {
setAllowedTimeOutOfZone(penaltySettings.allowedTimeOutOfZone.toString());
}
}, [zoneSettings, penaltySettings]);
function addPolygon(polygon) {
// Polygons
setPolygons([...polygons, polygon]);
// Durations
setDurations([...durations, defaultDuration]);
}
function removePolygon(i) {
// Polygons
const newPolygons = [...polygons];
newPolygons.splice(i, 1);
setPolygons(newPolygons);
// Durations
const newDurations = [...durations];
newDurations.splice(i, 1);
setDurations(newDurations);
}
function updateDuration(i, duration) {
const newDurations = [...durations];
newDurations[i] = duration;
setDurations(newDurations);
}
function handleSettingsSubmit() {
const newSettings = {polygons: polygons, durations: durations};
changeZoneSettings(newSettings);
changePenaltySettings({allowedTimeOutOfZone: Number(allowedTimeOutOfZone)});
}
return (
<div className='h-full w-full bg-white p-3 gap-3 flex flex-row shadow-2xl'>
<div className="h-full w-full">
<PolygonZonePicker polygons={polygons} addPolygon={addPolygon} removePolygon={removePolygon} />
</div>
<div className="h-full w-1/6 flex flex-col gap-3">
<div className="w-full text-center">
<h2 className="text-xl">Reduction order</h2>
</div>
<ul className="w-full h-full bg-gray-300">
{durations.map((duration, i) => (
<li key={i} className="w-full bg-white flex flex-row gap-2 items-center justify-between p-1">
<p>Zone {i+1}</p>
<div className="w-16 h-10">
<TextInput value={duration} onChange={(e) => updateDuration(i, e.target.value)}/>
</div>
</li>
))}
</ul>
<div className="w-full flex flex-row gap-2 items-center justify-between">
<p>Timeout</p>
<div className="w-16 h-10">
<TextInput value={allowedTimeOutOfZone} onChange={(e) => setAllowedTimeOutOfZone(e.target.value)} />
</div>
</div>
<div className="w-full h-15">
<GreenButton onClick={handleSettingsSubmit}>Apply</GreenButton>
</div>
</div>
</div>
);
}

View File

@@ -1,122 +0,0 @@
import React, { useEffect, useRef, useState } from 'react'
import { TextInput } from '../util/textInput'
import { BlueButton, RedButton } from '../util/button';
import useAdmin from '@/hook/useAdmin';
import dynamic from 'next/dynamic';
import { env } from 'next-runtime-env';
import { GameState } from '@/util/gameState';
// Imported at runtime and not at compile time
const PlacementMap = dynamic(() => import('./placementMap'), { ssr: false });
export default function TeamEdit({ selectedTeamId, setSelectedTeamId }) {
const teamImage = useRef(null);
const [avgSpeed, setAvgSpeed] = useState(0); // Speed in m/s
const [newTeamName, setNewTeamName] = React.useState('');
const { updateTeam, getTeamName, removeTeam, getTeam, teams, gameState, startDate } = useAdmin();
const [team, setTeam] = useState({});
const NEXT_PUBLIC_SOCKET_HOST = env("NEXT_PUBLIC_SOCKET_HOST");
const SERVER_URL = (NEXT_PUBLIC_SOCKET_HOST == "localhost" ? "http://" : "https://") + NEXT_PUBLIC_SOCKET_HOST + "/back";
useEffect(() => {
let team = getTeam(selectedTeamId);
if (team != undefined) {
setNewTeamName(team.name);
setTeam(team);
}
teamImage.current.src = SERVER_URL + "/photo/my?team=" + selectedTeamId + "&t=" + new Date().getTime();
}, [selectedTeamId, teams])
// Update the average speed
useEffect(() => {
const time = Math.floor((team.finishDate ? team.finishDate - startDate : Date.now() - startDate) / 1000);
setAvgSpeed(team.distance/time);
}, [team.distance, team.finishDate]);
function handleRename(e) {
e.preventDefault();
updateTeam(team.id, { name: newTeamName });
}
function handleRemove() {
removeTeam(team.id);
setSelectedTeamId(null);
}
function handleAddPenalty(increment) {
let newPenalties = team.penalties + increment;
newPenalties = Math.max(0, newPenalties);
newPenalties = Math.min(3, newPenalties);
updateTeam(team.id, { penalties: newPenalties });
}
function formatTimeHours(time) {
// time is in seconds
if (!Number.isInteger(time)) return "Inconnue";
if (time < 0) time = 0;
const hours = Math.floor(time / 3600);
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
return String(hours).padStart(2,"0") + ":" + String(minutes).padStart(2,"0") + ":" + String(seconds).padStart(2,"0");
}
return (team &&
<div className='flex flex-row w-full h-full gap-2'>
<div className='flex w-1/2 flex-col h-1/2 gap-2'>
<h2 className='text-2xl text-center'>Actions</h2>
<form className='flex flex-row' onSubmit={handleRename}>
<div className='w-4/5'>
<TextInput name="teamName" label='Team name' value={newTeamName} onChange={(e) => setNewTeamName(e.target.value)} />
</div>
<div className='w-2/5'>
<BlueButton type="submit">Rename</BlueButton>
</div>
</form>
<div className='flex flex-row'>
<BlueButton onClick={() => {updateTeam(team.id, { captured: !team.captured }); team.finishDate = Date.now()}}>{team.captured ? "Revive" : "Capture"}</BlueButton>
<RedButton onClick={handleRemove}>Remove</RedButton>
</div>
<p className='text-2xl text-center w-full'>Starting zone</p>
<PlacementMap area={team.startingArea} setArea={(startingArea) => updateTeam(team.id, { startingArea })} markerPosition={team?.currentLocation} />
</div>
<div className='flex w-1/2 flex-col h-min gap-2 items-center'>
<h2 className='text-2xl text-center'>Team details</h2>
<div className='w-3/5'>
<img className='self-stretch' ref={teamImage} onError={(e) => {e.target.src = "/images/missing_image.jpg"}} />
</div>
<div className='flex flex-col gap-3'>
<div>
<p>Secret : {String(team.id).padStart(6, '0').replace(/(\d{3})(\d{3})/, '$1 $2')}</p>
<p>Capture code : {String(team.captureCode).padStart(4, '0')}</p>
</div>
<div>
<p>Chasing : {getTeamName(team.chasing)}</p>
<p>Chased by : {getTeamName(team.chased)}</p>
</div>
{gameState == GameState.PLAYING &&
<div>
<p>Distance: { (team.distance / 1000).toFixed(1) }km</p>
<p>Time : {formatTimeHours(Math.floor((team.finishDate ? team.finishDate - startDate : Date.now() - startDate) / 1000))}</p>
<p>Average speed : {(avgSpeed*3.6).toFixed(1)}km/h</p>
<p>Captures : {team.nCaptures}</p>
<p>Sent location : {team.nSentLocation}</p>
<p>Oberved : {team.nObserved}</p>
</div>
}
<div>
<p>Phone model : {team.phoneModel ?? "Unknown"}</p>
<p>Phone name : {team.phoneName ?? "Unknown"}</p>
<p>Battery: {team.battery ? team.battery + "%" : "Unknown"}</p>
</div>
<div className='flex flex-row'>
<p>Penalties :</p>
<button className='w-7 h-7 mx-4 bg-blue-600 hover:bg-blue-500 text-md ease-out duration-200 text-white shadow-sm rounded' onClick={() => handleAddPenalty(-1)}>-</button>
<p>{team.penalties}</p>
<button className='w-7 h-7 mx-4 bg-blue-600 hover:bg-blue-500 text-md ease-out duration-200 text-white shadow-sm rounded' onClick={() => handleAddPenalty(1)}>+</button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,135 +0,0 @@
import useAdmin from "@/hook/useAdmin";
import { GameState } from '@/util/gameState';
import { useEffect, useState } from "react";
import { env } from 'next-runtime-env';
function DotLine({ label, value }) {
return (
<div className="flex items-center">
<span className="whitespace-nowrap text-m">{label}</span>
<span
className="flex-1 mx-2 overflow-hidden whitespace-nowrap text-black font-bold select-none"
aria-hidden="true"
>
{" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "}
</span>
<span className="whitespace-nowrap text-m">{value}</span>
</div>
);
}
function IconValue({ color, icon, value }) {
return (
<div className="flex flex-row gap-2">
<img src={`/icons/${color}${icon}.png`} className="w-6 h-6" />
<p className={`text-custom-${color}`}>{value}</p>
</div>
);
}
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: "Placée", color: "text-custom-green" },
notready: { label: "Non placée", color: "text-custom-red" },
waiting: { label: "En attente", color: "text-custom-grey" },
};
function getStatus(team, gamestate) {
switch (gamestate) {
case GameState.SETUP:
return TEAM_STATUS.waiting;
case GameState.PLACEMENT:
return team.ready ? TEAM_STATUS.ready : TEAM_STATUS.notready;
case GameState.PLAYING:
return team.captured ? TEAM_STATUS.captured : team.outofzone ? TEAM_STATUS.outofzone : TEAM_STATUS.playing;
case GameState.FINISHED:
return team.captured ? TEAM_STATUS.captured : TEAM_STATUS.playing;
}
}
export default function TeamInformation({ selectedTeamId, onClose }) {
const { getTeam, getTeamName, startDate, gameState } = useAdmin();
const [imgSrc, setImgSrc] = useState("");
const team = getTeam(selectedTeamId);
const NO_VALUE = "XX";
const NEXT_PUBLIC_SOCKET_HOST = env("NEXT_PUBLIC_SOCKET_HOST");
const SERVER_URL = (NEXT_PUBLIC_SOCKET_HOST == "localhost" ? "http://" : "https://") + NEXT_PUBLIC_SOCKET_HOST + "/back";
useEffect(() => {
setImgSrc(`${SERVER_URL}/photo/my?team=${selectedTeamId}&t=${Date.now()}`);
}, [selectedTeamId]);
if (!team) return null;
function formatTime(startDate) {
// startDate in milliseconds
const date = team.captured ? team.finishDate : Date.now();
if (date == null || startDate == null || startDate < 0) return NO_VALUE + ":" + NO_VALUE;
const seconds = Math.floor((date - startDate) / 1000);
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);
return `${m}:${s.toString().padStart(2, "0")}`;
}
function formatDistance(distance) {
// distance in meters
if (distance == null || distance < 0) return NO_VALUE + "km";
return `${Math.floor(distance / 100) / 10}km`;
}
function formatSpeed(distance, startDate) {
// distance in meters | startDate in milliseconds
const date = team.captured ? team.finishDate : Date.now();
if (distance == null || distance < 0 || date == null || startDate == null || date <= startDate) return NO_VALUE + "km/h";
const speed = distance / (date - startDate);
return `${Math.floor(speed * 36000) / 10}km/h`;
}
function formatDate(date) {
// date in milliseconds
const dateNow = Date.now();
if (date == null || dateNow <= date || dateNow - date >= 1_000_000) return NO_VALUE + "s";
return `${Math.floor((dateNow - date) / 1000)}s`;
}
return (
<div className="relative p-3 w-3/12 h-full flex flex-col gap-3">
<button className="absolute left-2 -top-1 text-black text-5xl" onClick={onClose} title="Fermer">x</button>
<p className={`text-2xl font-bold text-center ${getStatus(team, gameState).color} font-bold`}>{getStatus(team, gameState).label}</p>
<p className="text-4xl font-bold text-center">{team.name ?? NO_VALUE}</p>
<div className="flex justify-center">
<img src={imgSrc ? imgSrc : "/images/missing_image.jpg"} alt="Photo de l'équipe"/>
</div>
<div className="flex flex-row justify-between items-center">
<IconValue color={team.sockets.length > 0 ? "green" : "red"} icon="dude" value={team.sockets.length ?? NO_VALUE} />
<IconValue color={team.battery >= 20 ? "green" : "red"} icon="battery" value={(team.battery ?? NO_VALUE) + "%"} />
<IconValue
color={team.lastCurrentLocationDate != null && (Date.now() - team.lastCurrentLocationDate <= 30000) ? "green" : "red"}
icon="location" value={formatDate(team.lastCurrentLocationDate)}
/>
</div>
<div>
<DotLine label="ID d'équipe" value={String(team.id).padStart(6, '0').replace(/(\d{3})(\d{3})/, "$1 $2")} />
<DotLine label="ID de capture" value={String(team.captureCode).padStart(4, '0')} />
</div>
<div>
<DotLine label="Chasse" value={getTeamName(team.chasing) ?? NO_VALUE} />
<DotLine label="Chassé par" value={getTeamName(team.chased) ?? NO_VALUE} />
</div>
<div>
<DotLine label="Distance" value={formatDistance(team.distance)} />
<DotLine label="Temps de survie" value={formatTime(startDate)} />
<DotLine label="Vitesse moyenne" value={formatSpeed(team.distance, startDate)} />
<DotLine label="Captures" value={team.nCaptures ?? NO_VALUE} />
<DotLine label="Observations" value={team.nSentLocation ?? NO_VALUE} />
<DotLine label="Observé" value={team.nObserved ?? NO_VALUE} />
</div>
<div>
<DotLine label="Modèle" value={team.phoneModel ?? NO_VALUE} />
<DotLine label="Nom" value={team.phoneName ?? NO_VALUE} />
</div>
</div>
);
}

View File

@@ -1,72 +0,0 @@
import useAdmin from '@/hook/useAdmin';
import { GameState } from '@/util/gameState';
import { DragDropContext, Draggable, Droppable } from '@hello-pangea/dnd';
import React from 'react'
function reorder(list, startIndex, endIndex) {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
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='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>
)}
</Draggable>
);
}
export default function TeamList({selectedTeamId, onSelected}) {
const {teams, reorderTeams, gameState} = useAdmin();
function onDragEnd(result) {
if (!result.destination) return;
if (result.destination.index === result.source.index) return;
const newTeams = reorder(teams, result.source.index, result.destination.index);
reorderTeams(newTeams);
}
return (
<DragDropContext onDragEnd={onDragEnd} >
<Droppable droppableId='team-list'>
{provided => (
<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} gamestate={gameState} />
</li>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
);
}

View File

@@ -1,82 +0,0 @@
import useAdmin from '@/hook/useAdmin';
import { DragDropContext, Draggable, Droppable } from '@hello-pangea/dnd';
import React, { useState } from 'react'
function reorder(list, startIndex, endIndex) {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
function TeamListItem({ team, index }) {
const { removeTeam } = useAdmin();
function handleRemove() {
removeTeam(team.id);
}
return (
<Draggable draggableId={team.id.toString()} index={index} onClick={() => onSelected(team.id)}>
{provided => (
<div className='w-full p-2 bg-white flex flex-row items-center text-xl gap-3 font-bold' {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef}>
<div className='flex-1 w-full h-full flex flex-row items-center justify-between'>
<p>{team.name}</p>
<div className='flex flex-row items-center justify-between gap-3'>
<p>{String(team.id).padStart(6, '0').replace(/(\d{3})(\d{3})/, "$1 $2")}</p>
<img src="/icons/home.png" className="w-8 h-8" />
<img src="/icons/home.png" className="w-8 h-8" onClick={handleRemove} />
</div>
</div>
</div>
)}
</Draggable>
);
}
export default function TeamList() {
const { teams, reorderTeams, addTeam } = useAdmin();
const [teamName, setTeamName] = useState('');
function handleSubmit(e) {
e.preventDefault();
if (teamName !== "") {
addTeam(teamName);
setTeamName("")
}
}
function onDragEnd(result) {
if (!result.destination) return;
if (result.destination.index === result.source.index) return;
const newTeams = reorder(teams, result.source.index, result.destination.index);
reorderTeams(newTeams);
}
return (
<div className='w-full h-full flex flex-col gap-3'>
<form className='w-full flex flex-row gap-3' onSubmit={handleSubmit}>
<div className='w-full'>
<input name="teamName" label='Team name' value={teamName} onChange={(e) => setTeamName(e.target.value)} type="text" className="w-full h-full p-4 ring-1 ring-inset ring-gray-300" />
</div>
<div className='w-1/5'>
<button type="submit" className="w-full h-full bg-custom-light-blue hover:bg-blue-500 transition text-3xl font-bold">+</button>
</div>
</form>
<DragDropContext onDragEnd={onDragEnd} >
<Droppable droppableId='team-list'>
{provided => (
<ul className='w-full h-full gap-1 flex flex-col bg-gray-300 p-1' ref={provided.innerRef} {...provided.droppableProps}>
{teams.map((team, i) => (
<li key={team.id}>
<TeamListItem index={i} team={team} />
</li>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
</div>
);
}

View File

@@ -1,60 +0,0 @@
import useAdmin from '@/hook/useAdmin';
import { GameState } from '@/util/gameState';
import React from 'react';
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: "Placée", color: "text-custom-green" },
notready: { label: "Non placée", color: "text-custom-red" },
waiting: { label: "En attente", color: "text-custom-grey" },
};
function getStatus(team, gamestate) {
switch (gamestate) {
case GameState.SETUP:
return TEAM_STATUS.waiting;
case GameState.PLACEMENT:
return team.ready ? TEAM_STATUS.ready : TEAM_STATUS.notready;
case GameState.PLAYING:
return team.captured ? TEAM_STATUS.captured : team.outofzone ? TEAM_STATUS.outofzone : TEAM_STATUS.playing;
case GameState.FINISHED:
return team.captured ? TEAM_STATUS.captured : TEAM_STATUS.playing;
}
}
function TeamListItem({ itemSelected, team }) {
const { gameState } = useAdmin();
const status = getStatus(team, gameState);
return (
<div className={'w-full p-2 bg-white flex flex-row gap-3 justify-between cursor-pointer' + (itemSelected ? " outline outline-4 outline-black" : "")}>
<div className='flex flex-row items-center gap-3'>
<div className='flex flex-row gap-1'>
<img src={team.sockets.length > 0 ? "/icons/greendude.png" : "/icons/reddude.png"} className="w-4 h-4" />
<img src={team.battery > 20 ? "/icons/greenbattery.png" : "/icons/redbattery.png"} className="w-4 h-4" />
<img src={team.lastCurrentLocationDate != null && (Date.now() - team.lastCurrentLocationDate <= 30000) ? "/icons/greenlocation.png" : "/icons/redlocation.png"} className="w-4 h-4" />
</div>
<p className={`text-xl font-bold`}>{team.name}</p>
</div>
<p className={`text-xl font-bold ${status.color}`}>
{status.label}
</p>
</div>
);
}
export default function TeamList({selectedTeamId, onSelected}) {
const { teams } = useAdmin();
return (
<ul className='h-full gap-1 flex flex-col'>
{teams.map((team) => (
<li key={team.id} onClick={() => onSelected(team.id)}>
<TeamListItem itemSelected={selectedTeamId === team.id} team={team} />
</li>
))}
</ul>
);
}

View File

@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import "leaflet/dist/leaflet.css";
import { useMap } from "react-leaflet";
import "leaflet/dist/leaflet.css";
export function MapPan(props) {
const map = useMap();

View File

@@ -1,75 +0,0 @@
import useGame from "@/hook/useGame";
import { useEffect, useState } from "react"
import { BlueButton, GreenButton } from "../util/button";
import { TextInput } from "../util/textInput";
import useTeamConnexion from "@/context/teamConnexionContext";
import EnemyTeamModal from "./enemyTeamModal";
export default function ActionDrawer() {
const [visible, setVisible] = useState(false);
const [enemyCaptureCode, setEnemyCaptureCode] = useState("");
const { sendCurrentPosition, name, captureCode, capture, locationSendDeadline, penalties } = useGame();
const {logout} = useTeamConnexion();
const [timeLeftBeforePenalty, setTimeLeftBeforePenalty] = useState(0);
const [enemyModalVisible, setEnemyModalVisible] = useState(false);
useEffect(() => {
const interval = setInterval(() => {
console.log(locationSendDeadline)
const timeLeft = locationSendDeadline - Date.now();
setTimeLeftBeforePenalty(Math.floor(timeLeft / 1000 / 60));
}, 1000);
return () => clearInterval(interval);
}, [locationSendDeadline]);
function handleCapture() {
capture(enemyCaptureCode);
setEnemyCaptureCode("");
}
return (
<div className={"fixed w-screen bottom-0 z-10 bg-gray-100 flex justify-center rounded-t-2xl transition-all duration-200 flex flex-col " + (visible ? "h-full" : "h-20")}>
<img src="/icons/arrow_up.png" className={"w-full object-scale-down h-ful max-h-20 transition-all cursor-pointer duration-200 " + (visible && "rotate-180")} onClick={() => setVisible(!visible)} />
{visible && <div className="flex justify-between flex-col w-full h-full">
<div className="flex flex-row justify-around">
<img src="/icons/logout.png" onClick={logout} className='p-3 mx-2 w-14 h-14 bg-red-500 rounded-lg cursor-pointer bg-red z-20' />
</div>
<div className='shadow-2xl bg-white p-1 flex flex-col text-center mb-1 mx-auto w-4/5 rounded'>
<div>
<span className='text-2xl text-black'>{name}</span>
</div>
<div className='text-gray-700'>
<span> Capture code </span>
<span className='text-lg text-black'>{String(captureCode).padStart(4,"0")}</span>
</div>
<div className='text-gray-700'>
<span className='text-lg text-black'>{timeLeftBeforePenalty}min</span>
<span> before penalty</span>
</div>
<div className='w-1/2 flex flex-row justify-center mx-auto'>
{Array.from({ length: penalties }).map((_, i) => <div key={i} className='min-h-5 m-2 min-w-5 bg-red-400'></div>)}
{Array.from({ length: 3-penalties }).map((_, i) => <div key={i} className='min-h-5 m-2 min-w-5 bg-green-400'></div>)}
</div>
</div>
<div className="h-20">
<BlueButton onClick={sendCurrentPosition} className="h-10">Update position</BlueButton>
</div>
<div className="p-5 shadow-lg bg-white">
<div className="text-center text-2xl">Target</div>
<div className="h-20 my-1">
<GreenButton onClick={() => setEnemyModalVisible(true)}>See target info</GreenButton>
</div>
<div className="h-20 flex flex-row">
<TextInput inputMode="numeric" placeholder="Enemy code" value={enemyCaptureCode} onChange={(e) => setEnemyCaptureCode(e.target.value)} />
<GreenButton onClick={handleCapture}>Capture target</GreenButton>
</div>
</div>
{/* <div className="h-20">
<RedButton onClick={sendCurrentPosition}>Signal emergency</RedButton>
</div> */}
</div>
}
<EnemyTeamModal visible={enemyModalVisible} onClose={() => setEnemyModalVisible(false)} />
</div>
)
}

View File

@@ -1,39 +0,0 @@
import useGame from "@/hook/useGame";
import { RedButton } from "../util/button";
import { useEffect, useRef } from "react";
import { env } from 'next-runtime-env';
export default function EnemyTeamModal({ visible, onClose }) {
const { teamId, enemyName } = useGame();
const imageRef = useRef(null);
useEffect(() => {
if (visible) {
refreshImage();
}
}, [visible]);
function refreshImage() {
imageRef.current.src = SERVER_URL + "/photo/enemy?team=" + teamId.toString() + "&t=" + new Date().getTime();
}
var protocol = "https://";
const NEXT_PUBLIC_SOCKET_HOST = env("NEXT_PUBLIC_SOCKET_HOST");
if (NEXT_PUBLIC_SOCKET_HOST == "localhost") {
protocol = "http://";
}
const SERVER_URL = protocol + NEXT_PUBLIC_SOCKET_HOST + "/back";
console.log(SERVER_URL);
return (visible &&
<>
<div className='fixed w-screen h-screen bg-black bg-opacity-50 z-10 text-center'></div>
<div className='fixed w-11/12 h-5/6 p-5 z-20 mx-auto inset-x-0 my-auto inset-y-0 flex flex-col justify-center rounded-xl transition-all shadow-xl bg-white '>
<h1 className="w-full text-center text-3xl mb-5">{enemyName}</h1>
<img ref={imageRef} src={SERVER_URL + "/photo/enemy?team=" + teamId.toString()} className='w-full h-full object-contain' />
<div className="h-20">
<RedButton onClick={onClose}>Close</RedButton>
</div>
</div>
</>
)
}

View File

@@ -1,19 +0,0 @@
import { useState } from "react";
import { BlueButton } from "../util/button";
import { TextInput } from "../util/textInput";
export default function LoginForm({ onSubmit, title, placeholder, buttonText}) {
const [value, setValue] = useState("");
function handleSubmit(e) {
e.preventDefault();
setValue("");
onSubmit(value);
}
return (
<form className="bg-white shadow-md max-w mx-auto p-5 mx-10 flex flex-col space-y-4" onSubmit={handleSubmit}>
<h1 className="text-2xl font-bold text-center text-gray-700">{title}</h1>
<TextInput inputMode="numeric" placeholder={placeholder} value={value} onChange={(e) => setValue(e.target.value)} name="team-id"/>
<BlueButton type="submit">{buttonText}</BlueButton>
</form>
)
}

View File

@@ -1,105 +0,0 @@
import React, { useEffect, useState } from 'react'
import { Circle, MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet'
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css'
import "leaflet-defaulticon-compatibility";
import "leaflet/dist/leaflet.css";
import useGame from '@/hook/useGame';
import useTeamContext from '@/context/teamContext';
const DEFAULT_ZOOM = 14;
// Pan to the center of the map when the position of the user is updated for the first time
function MapPan(props) {
const map = useMap();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!initialized && props.center) {
map.flyTo(props.center, DEFAULT_ZOOM, { animate: false });
setInitialized(true)
}
}, [props.center]);
return null;
}
function LiveZone() {
const { zone } = useTeamContext();
console.log('Zone', zone);
return zone && <Circle center={zone.center} radius={zone.radius} color='blue' fill={false} />
}
function ZoneExtremities() {
const { zoneExtremities } = useTeamContext();
console.log('Zone extremities', zoneExtremities);
return zoneExtremities?.begin && zoneExtremities?.end && <>
{/* <Circle center={zoneExtremities.begin.center} radius={zoneExtremities.begin.radius} color='black' fill={false} /> */}
<Circle center={zoneExtremities.end.center} radius={zoneExtremities.end.radius} color='red' fill={false} />
</>
}
export function LiveMap({ ...props }) {
const { currentPosition, enemyPosition } = useGame();
useEffect(() => {
console.log('Current position', currentPosition);
}, [currentPosition]);
return (
<MapContainer {...props} className='min-h-full z-0' center={[0, 0]} zoom={0} 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"
/>
{currentPosition && <Marker position={currentPosition} icon={new L.Icon({
iconUrl: '/icons/location.png',
iconSize: [30, 30],
iconAnchor: [15, 15],
popupAnchor: [0, -15],
shadowSize: [30, 30],
})}>
<Popup>
Votre position
</Popup>
</Marker>}
{enemyPosition && <Marker position={enemyPosition} icon={new L.Icon({
iconUrl: '/icons/target.png',
iconSize: [30, 30],
iconAnchor: [15, 15],
popupAnchor: [0, -15],
shadowSize: [30, 30],
})}>
<Popup>
Position de l&apos;ennemi
</Popup>
</Marker>}
<MapPan center={currentPosition} />
<LiveZone />
<ZoneExtremities />
</MapContainer>
)
}
export function PlacementMap({ ...props }) {
const { currentPosition, startingArea } = useGame();
return (
<MapContainer {...props} className='min-h-full w-full z-0' center={[0, 0]} zoom={0} 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"
/>
{currentPosition && <Marker position={currentPosition} icon={new L.Icon({
iconUrl: '/icons/location.png',
iconSize: [30, 30],
iconAnchor: [15, 15],
popupAnchor: [0, -15],
shadowSize: [30, 30],
})}>
<Popup>
Votre position
</Popup>
</Marker>}
<MapPan center={currentPosition} />
{startingArea && <Circle center={startingArea?.center} radius={startingArea?.radius} color='blue' />}
</MapContainer>
)
}

View File

@@ -1,56 +0,0 @@
import { useSocketListener } from "@/hook/useSocketListener";
import { useEffect, useState } from "react";
export default function Notification({ socket }) {
const [visible, setVisible] = useState(false);
const [timeoutId, setTimeoutId] = useState(null);
const [notification, setNotification] = useState(null);
useSocketListener(socket, "error", (notification) => {
console.log("error", notification);
setNotification({ type: "error", text: notification });
setVisible(true);
});
useSocketListener(socket, "success", (notification) => {
console.log("success", notification);
setNotification({ type: "success", text: notification });
setVisible(true);
});
useSocketListener(socket, "warning", (notification) => {
console.log("warning", notification);
setNotification({ type: "warning", text: notification });
setVisible(true);
});
// Hide the notification after 5 seconds
useEffect(() => {
console.log({ visible });
if (visible && notification?.text != undefined) {
clearTimeout(timeoutId);
if (notification?.type == "success") {
setTimeoutId(setTimeout(() => {
setVisible(false);
}, 3000));
}
}
}, [visible]);
const bgColorMap = {
error: "bg-red-500 text-white",
success: "bg-green-500",
warning: "bg-yellow-500"
}
const classNames = 'fixed relative w-11/12 p-5 z-30 mx-auto inset-x-0 flex justify-center rounded-xl transition-all shadow-xl ' + (visible ? "top-5 " : "-translate-y-full ");
return (
Object.keys(bgColorMap).map((key) =>
notification?.type == key &&
<div key={key} className={classNames + bgColorMap[key]} onClick={() => setVisible(false)}>
<p className="absolute top-2 right-2 p-2 rounded-l text-3xl bg-white">x</p>
<p className='text-center text-xl'>{notification?.text}</p>
</div>
));
}

View File

@@ -1,19 +0,0 @@
import useTeamConnexion from "@/context/teamConnexionContext";
import useGame from "@/hook/useGame"
export default function PlacementOverlay() {
const { name, ready } = useGame();
const {logout} = useTeamConnexion();
return (
<>
<img src="/icons/logout.png" onClick={logout} className='w-12 h-12 bg-red-500 p-2 top-1 right-1 rounded-lg cursor-pointer bg-red fixed z-20' />
<div className='fixed top-0 p-3 w-full bg-gray-300 shadow-xl rounded-b-xl flex flex-col z-10 justify-center items-center'>
<div className='text-2xl my-3'>Placement</div>
<div className='text-md'>{name}</div>
{!ready && <div className='text-lg font-semibold text-red-700'>Positionez vous dans le cercle</div>}
{ready && <div className='text-lg font-semibold text-green-700 text-center'>Restez dans le cercle en attendant que la partie commence</div>}
</div>
</>
)
}

View File

@@ -1,56 +0,0 @@
import useGame from "@/hook/useGame"
import { GreenButton, LogoutButton } from "../util/button";
import { useRef } from "react";
import useTeamContext from "@/context/teamContext";
import { env } from 'next-runtime-env';
export default function WaitingScreen() {
const { name, teamId } = useGame();
const { gameSettings } = useTeamContext();
const imageRef = useRef(null);
const NEXT_PUBLIC_SOCKET_HOST = env("NEXT_PUBLIC_SOCKET_HOST");
var protocol = "https://";
if (NEXT_PUBLIC_SOCKET_HOST == "localhost") {
protocol = "http://";
}
const SERVER_URL = protocol + NEXT_PUBLIC_SOCKET_HOST + "/back";
console.log(SERVER_URL);
function sendImage() {
let data = new FormData();
data.append('file', document.querySelector('input[type="file"]').files[0]);
fetch(SERVER_URL + "/upload?team=" + teamId.toString() , {
method: 'POST',
body: data
}).then((response) => {
console.log(response);
refreshImage();
});
}
function refreshImage() {
imageRef.current.src = SERVER_URL + "/photo/my?team=" + teamId.toString() + "&t=" + new Date().getTime();
}
return (
<div className='h-full flex flex-col items-center justify-center'>
<LogoutButton />
<div className='text-4xl mt-10 text-center'>
Equipe : {name}
</div>
<div className='text-2xl text-center'>
{gameSettings?.waitingMessage}
</div>
<div className='text-2xl text-center my-10'>
<p>Uploadez une photo tous les membres de l&apos;équipe sont visibles</p>
<input type="file" name="file" accept="image/*" className=" my-5 block w-full text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"/>
<div className="h-20">
<GreenButton onClick={sendImage}>Envoyer</GreenButton>
</div>
</div>
{teamId && <img ref={imageRef} src={SERVER_URL + "/photo/my?team=" + teamId.toString()} className='w-screen h-1/2 object-contain' />}
</div>
)
}