Restructuration of the project folders

This commit is contained in:
Sebastien Riviere
2026-02-13 16:06:50 +01:00
parent 5f16500634
commit c1f1688794
188 changed files with 265 additions and 301 deletions

View File

@@ -0,0 +1,80 @@
import { Fragment, useEffect, useState } from "react";
import { Arrow, CircleZone, PolygonZone, Position, Tag } from "@/components/layer";
import { CustomMapContainer, MapEventListener, MapPan } from "@/components/map";
import useAdmin from "@/hook/useAdmin";
import { GameState, ZoneTypes } from "@/util/types";
import { mapZooms } from "@/util/configurations";
export default function LiveMap({ selectedTeamId, onSelected, isFocusing, setIsFocusing, mapStyle, showZones, showNames, showArrows }) {
const { zoneType, zoneExtremities, teams, nextZoneDate, getTeam, gameState } = useAdmin();
const [timeLeftNextZone, setTimeLeftNextZone] = useState(null);
const [isFullScreen, setIsFullScreen] = useState(false);
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 || 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 Zones() {
if (!(showZones && gameState == GameState.PLAYING)) return null;
switch (zoneType) {
case ZoneTypes.CIRCLE:
return (<>
<CircleZone circle={zoneExtremities.begin} color={mapStyle.currentZoneColor} />
<CircleZone circle={zoneExtremities.end} color={mapStyle.nextZoneColor} />
</>);
case ZoneTypes.POLYGON:
return (<>
<PolygonZone polygon={zoneExtremities.begin?.polygon} color={mapStyle.currentZoneColor} />
<PolygonZone polygon={zoneExtremities.end?.polygon} color={mapStyle.nextZoneColor} />
</>);
default:
return null;
}
}
return (
<div className={`${isFullScreen ? "fixed inset-0 z-[9999]" : "relative h-full w-full"}`}>
<CustomMapContainer mapStyle={mapStyle}>
{isFocusing && <MapPan center={getTeam(selectedTeamId)?.currentLocation} zoom={mapZooms.high} animate />}
<MapEventListener onDragStart={() => setIsFocusing(false)} onWheel={() => setIsFocusing(false)} />
<Zones/>
{teams.map((team) => team && <Fragment key={team.id}>
<CircleZone circle={team.startingArea} color={mapStyle.placementZoneColor} display={gameState == GameState.PLACEMENT && showZones}>
<Tag text={team.name} display={showNames} />
</CircleZone>
<Arrow pos1={team.currentLocation} pos2={getTeam(team.chasing)?.currentLocation} color={mapStyle.arrowColor} display={showArrows}/>
<Position position={team.currentLocation} color={mapStyle.playerColor} onClick={() => onSelected(team.id)} display={!team.captured}>
<Tag text={team.name} display={showNames} />
</Position>
</Fragment>)}
</CustomMapContainer>
{ gameState == GameState.PLAYING &&
<div className="absolute top-4 left-1/2 -translate-x-1/2 z-[1000] pointer-events-none flex flex-col items-center bg-white p-2 rounded-lg shadow-lg drop-shadow">
<p className="text-sm">Durée zone</p>
<p className="text-2xl font-bold">{formatTime(timeLeftNextZone)}</p>
</div>
}
<button className="absolute top-4 right-4 z-[1000] cursor-pointer bg-white p-3 rounded-full shadow-lg drop-shadow" onClick={() => setIsFullScreen(!isFullScreen)}>
<img src={`/icons/fullscreen.png`} className="w-8 h-8" />
</button>
</div>
)
}

View File

@@ -0,0 +1,125 @@
import { env } from 'next-runtime-env';
import { useEffect, useState } from "react";
import useAdmin from "@/hook/useAdmin";
import { getStatus } from '@/util/functions';
import { Colors, GameState } from '@/util/types';
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/${icon}/${color}.png`} className="w-6 h-6" />
<p style={{color: Colors[color]}}>{value}</p>
</div>
);
}
export default function TeamSidePanel({ selectedTeamId, onClose }) {
const { getTeam, startDate, gameState } = useAdmin();
const [imgSrc, setImgSrc] = useState("");
const [_, setRefreshKey] = useState(0);
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;
useEffect(() => {
const interval = setInterval(() => {
setRefreshKey(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
function formatTime(startDate, endDate) {
// startDate in milliseconds
if (endDate == null || startDate == null || startDate < 0) return NO_VALUE + ":" + NO_VALUE;
const seconds = Math.floor((endDate - 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, endDate) {
// distance in meters | startDate in milliseconds
if (distance == null || distance < 0 || endDate == null || startDate == null || endDate <= startDate) return NO_VALUE + "km/h";
const speed = distance / (endDate - 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="w-full h-full relative flex flex-col p-3 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" style={{color: getStatus(team, gameState).color}}>{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="user" value={team.sockets?.length ?? NO_VALUE} />
<IconValue color={team.battery >= 20 ? "green" : "red"} icon="battery" value={(team.battery ?? NO_VALUE) + "%"} />
<IconValue
color={team.lastCurrentLocationDate && (Date.now() - team.lastCurrentLocationDate <= 30000) ? "green" : "red"}
icon="location" value={formatDate(team.lastCurrentLocationDate)}
/>
</div>
<div>
<DotLine label="ID d'équipe" value={String(selectedTeamId).padStart(6, '0').replace(/(\d{3})(\d{3})/, "$1 $2")} />
<DotLine label="ID de capture" value={team.captureCode ? String(team.captureCode).padStart(4, '0') : NO_VALUE} />
</div>
{ gameState != GameState.FINISHED &&
<div>
<DotLine label="Chasse" value={getTeam(team.chasing)?.name ?? NO_VALUE} />
<DotLine label="Chassé par" value={getTeam(team.chased)?.name ?? NO_VALUE} />
</div>
}
{ (gameState == GameState.PLAYING || gameState == GameState.FINISHED) &&
<div>
<DotLine label="Distance" value={formatDistance(team.distance)} />
<DotLine label="Temps de survie" value={formatTime(startDate, team.finishDate || Date.now())} />
<DotLine label="Vitesse moyenne" value={formatSpeed(team.distance, startDate, team.finishDate || Date.now())} />
<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

@@ -0,0 +1,46 @@
import { List } from '@/components/list';
import useAdmin from '@/hook/useAdmin';
import { getStatus } from '@/util/functions';
import { useMemo } from 'react';
function TeamViewerItem({ team }) {
const { gameState } = useAdmin();
const status = getStatus(team, gameState);
const NO_VALUE = "XX";
return (
<div className={`w-full flex flex-row gap-3 p-2 ${team.captured ? 'bg-gray-200' : 'bg-white'} justify-between`}>
<div className='flex flex-row items-center gap-3'>
<div className='flex flex-row gap-1'>
<img src={`/icons/user/${team.sockets.length > 0 ? "green" : "red"}.png`} className="w-4 h-4" />
<img src={`/icons/battery/${team.battery >= 20 ? "green" : "red"}.png`} className="w-4 h-4" />
<img src={`/icons/location/${team.lastCurrentLocationDate && (Date.now() - team.lastCurrentLocationDate <= 30000) ? "green" : "red"}.png`} className="w-4 h-4" />
</div>
<p className="text-xl font-bold">{team.name ?? NO_VALUE}</p>
</div>
<p className="text-xl font-bold" style={{color: status.color}}>
{status.label}
</p>
</div>
);
}
export default function TeamViewer({selectedTeamId, onSelected}) {
const { teams } = useAdmin();
// Uncaptured teams first
const sortedTeams = useMemo(() => {
return [...teams].sort((a,b) => {
if (a.captured === b.captured) return 0;
return a.captured ? 1 : -1;
});
}, [teams]);
return (
<List array={sortedTeams} selectedId={selectedTeamId} onSelected={onSelected} >
{(team) => (
<TeamViewerItem team={team}/>
)}
</List>
);
}

View File

@@ -0,0 +1,12 @@
import { AdminConnexionProvider } from "@/context/adminConnexionContext";
import { AdminProvider } from "@/context/adminContext";
export default function AdminLayout({ children }) {
return (
<AdminConnexionProvider>
<AdminProvider>
{children}
</AdminProvider>
</AdminConnexionProvider>
);
}

View File

@@ -0,0 +1,26 @@
"use client";
import { useState } from "react";
import { useAdminConnexion } from '@/context/adminConnexionContext';
export default function AdminLoginPage() {
const {login, useProtect} = useAdminConnexion();
const [value, setValue] = useState("");
useProtect();
function handleSubmit(e) {
e.preventDefault();
setValue("");
login(value);
}
return (
<div className="w-full h-full flex items-center justify-center">
<form className="flex flex-col items-center gap-3 bg-white p-8 rounded-lg ring-1 ring-black" onSubmit={handleSubmit}>
<h1 className="text-2xl font-bold text-center text-gray-700">Connexion admin</h1>
<input name="team-id" className="w-60 h-12 text-center rounded ring-1 ring-inset ring-black placeholder:text-gray-400" placeholder="Mot de passe admin" value={value} onChange={(e) => setValue(e.target.value)}/>
<button className=" w-40 h-12 bg-blue-600 hover:bg-blue-500 text-l text-white rounded ease-out duration-200" type="submit">Se connecter</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,128 @@
"use client";
import { useState } from 'react';
import dynamic from "next/dynamic";
import Link from "next/link";
import { Section } from "@/components/section";
import { useAdminConnexion } from "@/context/adminConnexionContext";
import useAdmin from "@/hook/useAdmin";
import { GameState } from "@/util/types";
import { mapStyles } from '@/util/configurations';
import TeamSidePanel from "./components/teamSidePanel";
import TeamViewer from './components/teamViewer';
// Imported at runtime and not at compile time
const LiveMap = dynamic(() => import('./components/liveMap'), { ssr: false });
function MainTitle() {
return (
<div className='w-full bg-custom-light-blue gap-5 p-5 flex flex-row shadow-2xl'>
<img src="/icons/home.png" className="w-8 h-8" />
<h2 className="text-3xl font-bold">Page principale</h2>
</div>
);
}
function MapButton({ icon, ...props }) {
return (
<button className="w-16 h-16 bg-custom-light-blue rounded-full hover:bg-blue-500 transition flex items-center justify-center" {...props}>
<img src={`/icons/${icon}.png`} className="w-10 h-10" />
</button>
);
}
function ControlButton({ icon, ...props }) {
return (
<button className="w-[4.5rem] h-[4.5rem] bg-custom-light-blue rounded-lg hover:bg-blue-500 transition flex items-center justify-center" {...props}>
<img src={`/icons/${icon}.png`} className="w-10 h-10" />
</button>
);
}
export default function AdminPage() {
const { useProtect } = useAdminConnexion();
const { changeState, getTeam } = useAdmin();
const [selectedTeamId, setSelectedTeamId] = useState(null);
const [mapStyle, setMapStyle] = useState(mapStyles.default);
const [showZones, setShowZones] = useState(true);
const [showNames, setShowNames] = useState(true);
const [showArrows, setShowArrows] = useState(true);
const [isFocusing, setIsFocusing] = useState(true);
useProtect();
function onSelected(id) {
if (selectedTeamId == id && (!getTeam(id)?.currentLocation || isFocusing)) {
setSelectedTeamId(null);
setIsFocusing(false);
} else {
setSelectedTeamId(id);
setIsFocusing(true);
}
}
function switchMapStyle() {
setMapStyle(mapStyle == mapStyles.default ? mapStyles.satellite : mapStyles.default);
}
function switchZones() {
setShowZones(!showZones);
}
function switchNames() {
setShowNames(!showNames);
}
function switchArrows() {
setShowArrows(!showArrows);
}
return (
<div className='w-full h-full p-3 flex flex-row gap-3'>
<div className="h-full w-2/6 flex flex-col gap-3">
<MainTitle/>
<Section title="Contrôle" innerClassName='flex flex-row justify-between'>
<Link href="/admin/parameters">
<ControlButton icon="parameters" title="Accéder aux paramètres du jeu"/>
</Link>
{false && <ControlButton icon="play" title="Reprendre la partie" onClick={() => {}} />}
<ControlButton icon="reset" title="Réinitialiser la partie" onClick={() => changeState(GameState.SETUP)} />
<ControlButton icon="placement" title="Commencer les placements" onClick={() => changeState(GameState.PLACEMENT)} />
<ControlButton icon="begin" title="Lancer la traque" onClick={() => changeState(GameState.PLAYING)} />
</Section>
<Section title="Équipes" outerClassName="flex-1 min-h-0">
<TeamViewer selectedTeamId={selectedTeamId} onSelected={onSelected}/>
</Section>
</div>
<Section outerClassName='h-full flex-1' innerClassName='flex flex-col gap-3'>
<div className="flex-1 flex flex-row gap-3">
<div className="flex-1 h-full">
<LiveMap
selectedTeamId={selectedTeamId}
onSelected={onSelected}
isFocusing={isFocusing}
setIsFocusing={setIsFocusing}
mapStyle={mapStyle}
showZones={showZones}
showNames={showNames}
showArrows={showArrows}
/>
</div>
{selectedTeamId &&
<div className="w-3/12 h-full">
<TeamSidePanel selectedTeamId={selectedTeamId} onClose={() => setSelectedTeamId(null)}/>
</div>
}
</div>
<div className='w-full flex flex-row items-center justify-evenly py-2'>
<MapButton icon="mapstyle" title="Changer le style de la carte" onClick={switchMapStyle}/>
<MapButton icon="zones" title="Afficher/masquer les zones" onClick={switchZones}/>
<MapButton icon="names" title="Afficher/masquer les noms des équipes" onClick={switchNames}/>
<MapButton icon="arrows" title="Afficher/masquer les relations de traque" onClick={switchArrows}/>
{false && <MapButton icon="incertitude" title="Afficher/masquer les incertitudes de position"/>}
{false && <MapButton icon="path" title="Afficher/masquer la trace de l'équipe sélectionnée"/>}
{false && <MapButton icon="informations" title="Afficher/masquer les évènements de l'équipe sélectionnée"/>}
</div>
</Section>
</div>
)
}

View File

@@ -0,0 +1,111 @@
import { useEffect, useState } from "react";
import "leaflet/dist/leaflet.css";
import { CustomMapContainer, MapEventListener } from "@/components/map";
import { NumberInput } from "@/components/input";
import useAdmin from "@/hook/useAdmin";
import useMapCircleDraw from "@/hook/useCircleDraw";
import useLocalVariable from "@/hook/useLocalVariable";
import { defaultZoneSettings } from "@/util/configurations";
import { ZoneTypes } from "@/util/types";
import { CircleZone } from "@/components/layer";
const EditMode = {
MIN: 0,
MAX: 1
}
function Drawings({ minZone, setMinZone, maxZone, setMaxZone, editMode }) {
const { drawingCircle: drawingMaxCircle, handleLeftClick: maxLeftClick, handleRightClick: maxRightClick, handleMouseMove: maxHover } = useMapCircleDraw(maxZone, setMaxZone);
const { drawingCircle: drawingMinCircle, handleLeftClick: minLeftClick, handleRightClick: minRightClick, handleMouseMove: minHover } = useMapCircleDraw(minZone, setMinZone);
function MaxCircleZone() {
return (
drawingMaxCircle
? <CircleZone circle={drawingMaxCircle} color="blue" />
: <CircleZone circle={maxZone} color="blue" />
);
}
function MinCircleZone() {
return (
drawingMinCircle
? <CircleZone circle={drawingMinCircle} color="red" />
: <CircleZone circle={minZone} color="red" />
);
}
return (<>
<MapEventListener
onLeftClick={editMode == EditMode.MAX ? maxLeftClick : minLeftClick}
onRightClick={editMode == EditMode.MAX ? maxRightClick : minRightClick}
onMouseMove={editMode == EditMode.MAX ? maxHover : minHover}
/>
<MaxCircleZone/>
<MinCircleZone/>
</>);
}
export default function CircleZoneSelector({ display }) {
const {zoneSettings, outOfZoneDelay, updateSettings} = useAdmin();
const [localZoneSettings, setLocalZoneSettings, applyLocalZoneSettings] = useLocalVariable(zoneSettings, (e) => updateSettings({zone: e}));
const [localOutOfZoneDelay, setLocalOutOfZoneDelay, applyLocalOutOfZoneDelay] = useLocalVariable(outOfZoneDelay, (e) => updateSettings({outOfZoneDelay: e}));
const [editMode, setEditMode] = useState(EditMode.MAX);
useEffect(() => {
if (!localZoneSettings || localZoneSettings.type != ZoneTypes.CIRCLE) {
setLocalZoneSettings(defaultZoneSettings.circle);
}
}, [localZoneSettings]);
function setMinZone(minZone) {
setLocalZoneSettings({...localZoneSettings, min: minZone});
setEditMode(EditMode.MAX);
}
function setMaxZone(maxZone) {
setLocalZoneSettings({...localZoneSettings, max: maxZone});
setEditMode(EditMode.MIN);
}
function updateReductionCount(reductionCount) {
setLocalZoneSettings({...localZoneSettings, reductionCount: reductionCount});
}
function updateDuration(duration) {
setLocalZoneSettings({...localZoneSettings, duration: duration});
}
function handleSubmit() {
applyLocalZoneSettings();
applyLocalOutOfZoneDelay();
}
return (
<div className={display ? 'w-full h-full gap-3 flex flex-row' : "hidden"}>
{localZoneSettings && localZoneSettings.type == ZoneTypes.CIRCLE && <>
<div className="h-full flex-1">
<CustomMapContainer>
<Drawings minZone={localZoneSettings.min} setMinZone={setMinZone} maxZone={localZoneSettings.max} setMaxZone={setMaxZone} editMode={editMode} />
</CustomMapContainer>
</div>
<div className="h-full w-1/6 flex flex-col gap-3">
{editMode == EditMode.MAX && <button className="w-full h-16 text-lg text-white rounded bg-blue-600 hover:bg-blue-500" onClick={() => setEditMode(EditMode.MIN)}>Édition première zone</button>}
{editMode == EditMode.MIN && <button className="w-full h-16 text-lg text-white rounded bg-red-600 hover:bg-red-500" onClick={() => setEditMode(EditMode.MAX)}>Édition dernière zone</button>}
<div className="w-full flex flex-row gap-2 items-center justify-between">
<p>Nombre de rétrécissements</p>
<NumberInput id="reduction-number" value={localZoneSettings.reductionCount ?? ""} onChange={updateReductionCount} />
</div>
<div className="w-full flex flex-row gap-2 items-center justify-between">
<p>Durée d'une zone</p>
<NumberInput id="duration" value={localZoneSettings.duration ?? ""} onChange={updateDuration} />
</div>
<div className="w-full flex flex-row gap-2 items-center justify-between">
<p>Temps permis hors zone</p>
<NumberInput id="timeout-circle-selector" value={localOutOfZoneDelay ?? ""} onChange={setLocalOutOfZoneDelay} />
</div>
<button className="w-full h-16 text-lg text-white rounded bg-green-600 hover:bg-green-500" onClick={handleSubmit}>Appliquer</button>
</div>
</>}
</div>
);
}

View File

@@ -0,0 +1,30 @@
import { Section } from "@/components/section";
import useAdmin from "@/hook/useAdmin";
import useLocalVariable from "@/hook/useLocalVariable";
function MessageInput({title, ...props}) {
return (
<div className="w-full flex flex-row gap-3 items-center">
<p>{title}</p>
<input className="w-full p-1 rounded ring-1 ring-inset ring-gray-400 placeholder:text-gray-600" {...props} />
</div>
);
}
export default function Messages() {
const {messages, updateSettings} = useAdmin();
const [localGameSettings, setLocalGameSettings, applyLocalGameSettings] = useLocalVariable(messages, (e) => updateSettings({messages: e}));
function modifyLocalZoneSettings(key, value) {
setLocalGameSettings(prev => ({...prev, [key]: value}));
};
return (
<Section title="Messages" innerClassName="w-full h-full flex flex-col gap-3 items-center">
<MessageInput id="waiting" title="Attente  :" value={localGameSettings?.waiting ?? ""} onChange={(e) => modifyLocalZoneSettings("waiting", e.target.value)} onBlur={applyLocalGameSettings}/>
<MessageInput id="captured" title="Capture :" value={localGameSettings?.captured ?? ""} onChange={(e) => modifyLocalZoneSettings("captured", e.target.value)} onBlur={applyLocalGameSettings}/>
<MessageInput id="winner" title="Victoire :" value={localGameSettings?.winner ?? ""} onChange={(e) => modifyLocalZoneSettings("winner", e.target.value)} onBlur={applyLocalGameSettings}/>
<MessageInput id="loser" title="Défaite  :" value={localGameSettings?.loser ?? ""} onChange={(e) => modifyLocalZoneSettings("loser", e.target.value)} onBlur={applyLocalGameSettings}/>
</Section>
);
}

View File

@@ -0,0 +1,69 @@
import { useEffect, useState } from "react";
import { List } from "@/components/list";
import { CustomMapContainer, MapEventListener } from "@/components/map";
import useAdmin from '@/hook/useAdmin';
import useMultipleCircleDraw from "@/hook/useMultipleCircleDraw";
import { CircleZone, Tag } from "@/components/layer";
function Drawings({ placementZones, addZone, removeZone, handleRightClick }) {
const { handleLeftClick, handleRightClick: handleRightClickDrawing } = useMultipleCircleDraw(placementZones, addZone, removeZone, 30);
function modifiedHandleRightClick(e) {
handleRightClickDrawing(e);
handleRightClick();
}
return (<>
<MapEventListener onLeftClick={handleLeftClick} onRightClick={modifiedHandleRightClick} />
{ placementZones.map(placementZone =>
<CircleZone key={placementZone.id} circle={placementZone} color="blue">
<Tag text={placementZone.name} />
</CircleZone>
)}
</>);
}
export default function PlacementZoneSelector({ display }) {
const { teams, getTeam, placementTeam } = useAdmin();
const [selectedTeamId, setSelectedTeamId] = useState(null);
const [placementZones, setPlacementZones] = useState([]);
useEffect(() => {
setPlacementZones(teams.filter(team => team.startingArea).map(team => ({id: team.id, name: team.name, center: team.startingArea.center, radius: team.startingArea.radius})));
}, [teams]);
function addPlacementZone(center, radius) {
if (!selectedTeamId) return;
const placementZonesFiltered = placementZones.filter(placementZone => placementZone.id !== selectedTeamId);
const newZone = {id: selectedTeamId, name: getTeam(selectedTeamId).name, center: center, radius: radius};
placementTeam(selectedTeamId, newZone);
setPlacementZones([...placementZonesFiltered, newZone]);
}
function removePlacementZone(id) {
placementTeam(id, null);
setPlacementZones(placementZones.filter((placementZone) => placementZone.id !== id));
}
return (
<div className={display ? 'w-full h-full gap-3 flex flex-row' : "hidden"}>
<div className="h-full flex-1">
<CustomMapContainer>
<Drawings placementZones={placementZones} addZone={addPlacementZone} removeZone={removePlacementZone} handleRightClick={() => setSelectedTeamId(null)} />
</CustomMapContainer>
</div>
<div className="h-full w-1/6 flex flex-col gap-3">
<div className="w-full text-center">
<h2 className="text-xl">Équipes</h2>
</div>
<List array={teams} selectedId={selectedTeamId} onSelected={(id) => setSelectedTeamId(selectedTeamId != id ? id : null)}>
{ (team) =>
<div key={team.id} className="w-full flex flex-row items-center justify-between gap-2 p-2 bg-white">
<p className='text-xl font-bold'>{team.name}</p>
</div>
}
</List>
</div>
</div>
);
}

View File

@@ -0,0 +1,38 @@
import dynamic from "next/dynamic";
import { ZoneTypes } from "@/util/types";
import useLocalVariable from "@/hook/useLocalVariable";
import useAdmin from "@/hook/useAdmin";
// Imported at runtime and not at compile time
const CircleZoneSelector = dynamic(() => import('./circleZoneSelector'), { ssr: false });
const PolygonZoneSelector = dynamic(() => import('./polygonZoneSelector'), { ssr: false });
function ZoneTypeButton({title, onClick, isSelected}) {
const grayStyle = "bg-gray-300 hover:bg-gray-400";
const blueStyle = "bg-custom-light-blue";
return (
<div className={`flex justify-center items-center rounded-md cursor-pointer ${isSelected ? blueStyle : grayStyle}`} onClick={onClick}>
<p className="text-l font-bold p-2">{title}</p>
</div>
);
}
export default function PlayingZoneSelector({ display }) {
const { zoneType } = useAdmin();
const [localZoneType, setLocalZoneType] = useLocalVariable(zoneType, () => {});
return (
<div className={display ? 'w-full h-full gap-3 flex flex-col' : "hidden"}>
<div className="w-full flex flex-row gap-3 items-center">
<p className="text-l">Type de zone :</p>
<ZoneTypeButton title="Cercles" onClick={() => setLocalZoneType(ZoneTypes.CIRCLE)} isSelected={localZoneType == ZoneTypes.CIRCLE} />
<ZoneTypeButton title="Polygones" onClick={() => setLocalZoneType(ZoneTypes.POLYGON)} isSelected={localZoneType == ZoneTypes.POLYGON} />
</div>
<div className="w-full flex-1">
<CircleZoneSelector display={localZoneType == ZoneTypes.CIRCLE} />
<PolygonZoneSelector display={localZoneType == ZoneTypes.POLYGON} />
</div>
</div>
);
}

View File

@@ -0,0 +1,128 @@
import { useEffect, useState } from "react";
import { Polyline } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import { ReorderList } from "@/components/list";
import { CustomMapContainer, MapEventListener } from "@/components/map";
import { NumberInput } from "@/components/input";
import { Node, PolygonZone, Label } from "@/components/layer";
import useAdmin from "@/hook/useAdmin";
import useMapPolygonDraw from "@/hook/usePolygonDraw";
import useLocalVariable from "@/hook/useLocalVariable";
import { defaultZoneSettings } from "@/util/configurations";
import { ZoneTypes } from "@/util/types";
function Drawings({ localZoneSettings, addZone, removeZone }) {
const [polygons, setPolygons] = useState([]);
const { currentPolygon, highlightNodes, handleLeftClick, handleRightClick, handleMouseMove } = useMapPolygonDraw(polygons, addZone, removeZone);
useEffect(() => {
if (localZoneSettings.type == ZoneTypes.POLYGON) {
setPolygons(localZoneSettings.polygons.map(zone => zone.polygon));
}
}, [localZoneSettings]);
function getLabelPosition(polygon) {
const sum = polygon.reduce(
(acc, coord) => ({
lat: acc.lat + coord.lat,
lng: acc.lng + coord.lng
}),
{ lat: 0, lng: 0 }
);
// The calculated mean point can be out of the polygon
// Idea : take the mean point of the largest convex subpolygon
return {lat: sum.lat / polygon.length, lng: sum.lng / polygon.length};
}
return (<>
<MapEventListener onLeftClick={handleLeftClick} onRightClick={handleRightClick} onMouseMove={handleMouseMove} />
{localZoneSettings.polygons.map(zone =>
<PolygonZone key={zone.id} polygon={zone.polygon} color="black" opacity='0.5' >
<Label position={getLabelPosition(zone.polygon)} label={zone.id} color="white" />
</PolygonZone>
)}
{ currentPolygon.length > 0 && <>
<Polyline positions={currentPolygon} pathOptions={{ color: "red", weight: 3 }} />
<Node position={currentPolygon[0]} color="red" />
</>}
{highlightNodes.map((node, i) =>
<Node key={i} position={node} color="black" />
)}
</>);
}
export default function PolygonZoneSelector({ display }) {
const defaultDuration = 10;
const {zoneSettings, outOfZoneDelay, updateSettings} = useAdmin();
const [localZoneSettings, setLocalZoneSettings, applyLocalZoneSettings] = useLocalVariable(zoneSettings, (e) => updateSettings({zone: e}));
const [localOutOfZoneDelay, setLocalOutOfZoneDelay, applyLocalOutOfZoneDelay] = useLocalVariable(outOfZoneDelay, (e) => updateSettings({outOfZoneDelay: e}));
useEffect(() => {
if (!localZoneSettings || localZoneSettings.type != ZoneTypes.POLYGON) {
setLocalZoneSettings(defaultZoneSettings.polygon);
}
}, [localZoneSettings]);
function getNewPolygonName() {
const existingIds = new Set(localZoneSettings.polygons.map(zone => zone.id));
for (let i = 0; i < 26; i++) {
const letter = String.fromCharCode(65 + i);
if (!existingIds.has(letter)) {
return letter;
}
}
return "XXX";
}
function setLocalZoneSettingsPolygons(polygons) {
setLocalZoneSettings({type: localZoneSettings.type, polygons: polygons});
}
function addZone(polygon) {
setLocalZoneSettingsPolygons([...localZoneSettings.polygons, {id: getNewPolygonName(), polygon: polygon, duration: defaultDuration}]);
}
function removeZone(i) {
setLocalZoneSettingsPolygons(localZoneSettings.polygons.filter((_, index) => index !== i));
}
function updateDuration(id, duration) {
setLocalZoneSettingsPolygons(localZoneSettings.polygons.map(zone => zone.id === id ? {...zone, duration: duration} : zone));
}
function handleSubmit() {
applyLocalZoneSettings();
applyLocalOutOfZoneDelay();
}
return (
<div className={display ? 'w-full h-full gap-3 flex flex-row' : "hidden"}>
{localZoneSettings && localZoneSettings.type == ZoneTypes.POLYGON && <>
<div className="h-full flex-1">
<CustomMapContainer>
<Drawings localZoneSettings={localZoneSettings} addZone={addZone} removeZone={removeZone} />
</CustomMapContainer>
</div>
<div className="h-full w-1/6 flex flex-col gap-3">
<div className="w-full text-center">
<h2 className="text-xl">Ordre de réduction</h2>
</div>
<ReorderList droppableId="zones-order" array={localZoneSettings.polygons} setArray={setLocalZoneSettingsPolygons}>
{ (zone) =>
<div key={zone.id} className="w-full p-2 bg-white flex flex-row gap-2 items-center justify-between">
<p>Zone {zone.id}</p>
<NumberInput id={zone.id} value={zone.duration || ""} onChange={value => updateDuration(zone.id, value)}/>
</div>
}
</ReorderList>
<div className="w-full flex flex-row gap-2 items-center justify-between">
<p>Temps permis hors zone</p>
<NumberInput id="timeout-polygon-selector" value={localOutOfZoneDelay ?? ""} onChange={setLocalOutOfZoneDelay}/>
</div>
<button className="w-full h-16 text-lg text-white rounded bg-green-600 hover:bg-green-500" onClick={handleSubmit}>Appliquer</button>
</div>
</>}
</div>
);
}

View File

@@ -0,0 +1,59 @@
import { useState } from "react";
import { ReorderList } from '@/components/list';
import useAdmin from '@/hook/useAdmin';
import useLocalVariable from "@/hook/useLocalVariable";
import { NumberInput } from "@/components/input";
import { Section } from "@/components/section";
function TeamManagerItem({ team }) {
const { captureTeam, removeTeam } = useAdmin();
return (
<div className='w-full flex flex-row items-center justify-between p-2 gap-3 bg-white'>
<p className='text-xl font-bold'>{team.name}</p>
<div className='flex flex-row items-center justify-between gap-3'>
<p className='text-xl font-bold'>{String(team.id).padStart(6, '0').replace(/(\d{3})(\d{3})/, "$1 $2")}</p>
<img src={`/icons/heart/${team.captured ? "grey" : "pink"}.png`} className="w-8 h-8 cursor-pointer" onClick={() => captureTeam(team.id)} />
<img src="/icons/trash.png" className="w-8 h-8 cursor-pointer" onClick={() => removeTeam(team.id)} />
</div>
</div>
);
}
export default function TeamManager() {
const { teams, addTeam, reorderTeams, sendPositionDelay, updateSettings } = useAdmin();
const [teamName, setTeamName] = useState('');
const [localSendPositionDelay, setLocalSendPositionDelay, applyLocalSendPositionDelay] = useLocalVariable(sendPositionDelay, (e) => updateSettings({sendPositionDelay: e}));
function handleTeamSubmit(e) {
e.preventDefault();
if (teamName !== "") {
addTeam(teamName);
setTeamName("")
}
}
return (
<Section title="Équipes" outerClassName="flex-1 min-h-0" innerClassName="flex flex-col items-center gap-3">
<form className='w-full flex flex-row gap-3' onSubmit={handleTeamSubmit}>
<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>
<div className="w-full flex-1 min-h-0 ">
<ReorderList droppableId="team-manager" array={teams} setArray={(teams) => reorderTeams(teams.map(team => team.id))}>
{(team) => (
<TeamManagerItem team={team}/>
)}
</ReorderList>
</div>
<div className="w-full flex flex-row gap-2 items-center justify-between">
<p>Intervalle entre les envois de position</p>
<NumberInput id="position-update" value={localSendPositionDelay ?? ""} onChange={setLocalSendPositionDelay} onBlur={applyLocalSendPositionDelay} />
</div>
</Section>
);
}

View File

@@ -0,0 +1,65 @@
"use client";
import { useState } from "react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useAdminConnexion } from "@/context/adminConnexionContext";
import Messages from "./components/messages";
import TeamManager from './components/teamManager';
import PlayingZoneSelector from "./components/playingZoneSelector";
// Imported at runtime and not at compile time
const PlacementZoneSelector = dynamic(() => import('./components/placementZoneSelector'), { ssr: false });
const Tabs = {
PLACEMENT_ZONES: "placement_zones",
PLAYING_ZONES: "playing_zones",
}
function ParametersTitle() {
return (
<div className='w-full bg-custom-light-blue gap-5 p-5 flex flex-row shadow-2xl'>
<Link href="/admin">
<img src="/icons/backarrow.png" className="w-8 h-8" title="Main page" />
</Link>
<h2 className="text-3xl font-bold">Paramètres</h2>
</div>
);
}
function TabButton({title, onClick, isSelected}) {
const grayStyle = "bg-gray-300 hover:bg-gray-400";
const blueStyle = "bg-custom-light-blue";
return (
<div className={`flex-1 h-full flex justify-center items-center cursor-pointer ${isSelected ? blueStyle : grayStyle}`} onClick={onClick}>
<p className="text-2xl font-bold">{title}</p>
</div>
);
}
export default function ParametersPage() {
const { useProtect } = useAdminConnexion();
const [currentTab, setCurrentTab] = useState(Tabs.PLACEMENT_ZONES);
useProtect();
return (
<div className='w-full h-full p-3 flex flex-row gap-3'>
<div className="h-full w-2/6 gap-3 flex flex-col">
<ParametersTitle/>
<Messages/>
<TeamManager/>
</div>
<div className="h-full flex-1 flex flex-col bg-white shadow-2xl">
<div className="w-full h-20 flex flex-row bg-gray-300">
<TabButton title="Zones de placement" onClick={() => setCurrentTab(Tabs.PLACEMENT_ZONES)} isSelected={currentTab == Tabs.PLACEMENT_ZONES}/>
<TabButton title="Zones de jeu" onClick={() => setCurrentTab(Tabs.PLAYING_ZONES)} isSelected={currentTab == Tabs.PLAYING_ZONES}/>
</div>
<div className="w-full flex-1 p-3 bg-white">
<PlacementZoneSelector display={currentTab == Tabs.PLACEMENT_ZONES} />
<PlayingZoneSelector display={currentTab == Tabs.PLAYING_ZONES} />
</div>
</div>
</div>
);
}