Add Tournament form

This commit is contained in:
Owen Rees
2023-08-29 22:55:22 +02:00
parent 419a3dd0c0
commit d33d447f90
21 changed files with 924 additions and 110 deletions
+112
View File
@@ -0,0 +1,112 @@
"use client";
import { MapProps } from "@/types";
import { useMemo, useRef, ChangeEvent } from "react";
import { useTranslations } from "next-intl";
import { useSetAtom } from "jotai";
import { mapBoundsAtom } from "@/app/atoms";
import L from "leaflet";
import { MapContainer, TileLayer, Marker } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet-defaulticon-compatibility";
import MapEvents from "@/app/[lang]/components/MapEvents";
const Map = ({ position, setPosition, center }: MapProps) => {
const t = useTranslations("Map");
const latValue = position.lat.toFixed(4);
const lngValue = position.lng.toFixed(4);
const setMapBounds = useSetAtom(mapBoundsAtom);
const markerRef = useRef<L.Marker | null>(null);
const handleLatChange = ({ target }: ChangeEvent<HTMLInputElement>) => {
const newLat = Number(target.value);
setPosition((prevPosition) => ({ ...prevPosition, lat: newLat }));
};
const handleLngChange = ({ target }: ChangeEvent<HTMLInputElement>) => {
const newLng = Number(target.value);
setPosition((prevPosition) => ({ ...prevPosition, lng: newLng }));
};
const eventHandlers = useMemo(
() => ({
dragend() {
const marker = markerRef.current;
if (marker != null) {
setPosition(marker.getLatLng());
}
},
}),
[setPosition],
);
return (
<>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="lat"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("latLabel")}
</label>
<input
value={latValue}
onChange={handleLatChange}
type="number"
id="lat"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="lng"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("lngLabel")}
</label>
<input
value={lngValue}
onChange={handleLngChange}
type="number"
id="lng"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
required
/>
</div>
<section id="map" className="z-0 col-span-4 flex h-auto">
<MapContainer
center={center}
zoom={5}
scrollWheelZoom={false}
style={{ height: "600px", flexGrow: 1 }}
ref={(map) => {
if (map) {
setMapBounds(map.getBounds());
}
}}
>
<MapEvents />
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={position}
draggable={true}
ref={markerRef}
eventHandlers={eventHandlers}
/>
</MapContainer>
</section>
</>
);
};
export default Map;
@@ -0,0 +1,268 @@
"use client";
import dynamic from "next/dynamic";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useAtomValue } from "jotai";
import { franceCenterAtom } from "@/app/atoms";
import useTournamentForm from "@/hooks/useTournamentForm";
import InfoMessage from "@/app/[lang]/components/InfoMessage";
import {
handleTournamentSubmit,
handleClearTournamentForm,
} from "@/handlers/formHandlers";
import LoadingMap from "@/app/[lang]/components/LoadingMap";
const Map = dynamic(() => import("./Map"), {
ssr: false,
loading: LoadingMap,
});
const TournamentForm = () => {
const t = useTranslations("AddTournament");
const center = useAtomValue(franceCenterAtom);
const formRefs = useTournamentForm();
const [isSending, setIsSending] = useState(false);
const [responseMessage, setResponseMessage] = useState({
isSuccessful: false,
message: "",
});
return (
<>
<form
onSubmit={(e) =>
handleTournamentSubmit(
e,
t,
setIsSending,
setResponseMessage,
formRefs,
)
}
className="space-y-8"
>
<div className="grid grid-cols-4 items-start gap-6">
<div className="col-span-4">
<label
htmlFor="tournament-name"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("tournamentNameLabel")}
</label>
<input
ref={formRefs.tournamentNameRef}
type="text"
id="tournament-name"
className="item dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("tournamentNamePlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="date"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("dateLabel")}
</label>
<input
ref={formRefs.dateRef}
type="date"
id="date"
className="dark:shadow-sm-light block w-full content-center rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="url"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("urlLabel")}
</label>
<input
ref={formRefs.urlRef}
type="url"
id="url"
placeholder={t("urlPlaceholder")}
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="time-control"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("tcLabel")}
</label>
<select
ref={formRefs.timeControlRef}
id="time-control"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
defaultValue="Classical"
>
<option value="Classical">{t("tcOption1")}</option>
<option value="Rapid">{t("tcOption2")}</option>
<option value="Blitz">{t("tcOption3")}</option>
<option value="Other">{t("tcOption4")}</option>
</select>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="norm"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("normLabel")}
</label>
<select
ref={formRefs.normRef}
id="norm"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
defaultValue="false"
>
<option value="false">{t("normNo")}</option>
<option value="true">{t("normYes")}</option>
</select>
</div>
<div className="col-span-4">
<label
htmlFor="address"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("addressLabel")}
</label>
<input
ref={formRefs.addressRef}
type="text"
id="address"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("addressPlaceholder")}
required
/>
</div>
<div className="col-span-4 sm:col-span-2">
<label
htmlFor="town"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("townLabel")}
</label>
<input
ref={formRefs.townRef}
type="text"
id="town"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("townPlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="department"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("departmentLabel")}
</label>
<input
ref={formRefs.departmentRef}
type="text"
id="department"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("departmentPlaceholder")}
// required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="country"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("countryLabel")}
</label>
<input
ref={formRefs.countryRef}
type="text"
id="country"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("countryPlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="your-name"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("yourNameLabel")}
</label>
<input
ref={formRefs.yourNameRef}
type="text"
id="your-name"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("yourNamePlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<label
htmlFor="your-email"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("yourEmailLabel")}
</label>
<input
ref={formRefs.yourEmailRef}
type="email"
id="your-email"
className="dark:shadow-sm-light block w-full rounded-lg border border-gray-300 bg-gray-50 p-3 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("yourEmailPlaceholder")}
required
/>
</div>
<div className="col-span-4 row-span-2 sm:col-span-2">
<label
htmlFor="message"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("messageLabel")}
</label>
<textarea
ref={formRefs.messageRef}
id="message"
rows={6}
className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500"
placeholder={t("messagePlaceholder")}
// required
></textarea>
</div>
<Map
position={formRefs.position}
setPosition={formRefs.setPosition}
center={center}
/>
</div>
<button
disabled={isSending}
type="submit"
className="rounded-lg bg-primary-600 px-5 py-3 text-center text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:hover:bg-primary-700 dark:focus:ring-primary-800 sm:w-fit"
>
{isSending ? t("sending") : t("sendButton")}
</button>
<button
onClick={() => handleClearTournamentForm(formRefs, center)}
type="button"
className="ml-4 rounded-lg bg-primary-600 px-5 py-3 text-center text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:hover:bg-primary-700 dark:focus:ring-primary-800 sm:w-fit"
>
{t("clearForm")}
</button>
<InfoMessage responseMessage={responseMessage} />;
</form>
</>
);
};
export default TournamentForm;
+24
View File
@@ -0,0 +1,24 @@
import { useTranslations } from "next-intl";
import TournamentForm from "./TournamentForm";
export default function Contact() {
const t = useTranslations("AddTournament");
return (
<section className="grid place-items-center bg-white pb-20 dark:bg-gray-800">
<div className="mx-auto max-w-screen-md px-4 py-8 lg:py-16">
<h2
className="mb-4 text-center text-4xl font-extrabold tracking-tight text-gray-900 dark:text-white"
data-test="header2"
>
{t("title")}
</h2>
<p className="mb-8 text-center font-light text-gray-500 dark:text-gray-400 sm:text-xl lg:mb-16">
{t("info")}
</p>
<TournamentForm />
</div>
</section>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { ResponseMessage } from "@/types";
import { Dispatch, SetStateAction } from "react";
const InfoMessage = ({
responseMessage,
}: {
responseMessage: ResponseMessage;
}) => (
<p
className={`${
responseMessage.isSuccessful ? "text-green-600" : "text-red-600"
} italic`}
data-test="info-message"
>
{responseMessage.message}
</p>
);
export const clearMessage = (
setResponseMessage: Dispatch<SetStateAction<ResponseMessage>>,
) => {
setTimeout(() => {
setResponseMessage({
isSuccessful: false,
message: "",
});
}, 10000);
};
export default InfoMessage;
+12
View File
@@ -0,0 +1,12 @@
import { useTranslations } from "next-intl";
const LoadingMap = () => {
const t = useTranslations("Tournaments");
return (
<div className="grid h-content place-self-center bg-white text-center text-gray-900 dark:bg-gray-800 dark:text-white">
<p>{t("loading")}</p>
</div>
);
};
export default LoadingMap;
+31
View File
@@ -0,0 +1,31 @@
import { useEffect } from "react";
import { useSetAtom } from "jotai";
import { mapBoundsAtom } from "@/app/atoms";
import L from "leaflet";
import { useMapEvent } from "react-leaflet";
const MapEvents = () => {
const setMapBounds = useSetAtom(mapBoundsAtom);
const worldBounds = L.latLngBounds(L.latLng(-90, -180), L.latLng(90, 180));
const franceBounds = L.latLngBounds(
L.latLng(42.08, -5.12),
L.latLng(51.17, 9.53),
);
const map = useMapEvent("moveend", () => {
// Set the map bounds atoms when the user pans/zooms
setMapBounds(map.getBounds());
});
// viewport agnostic centering of France & max world bounds
useEffect(() => {
map.setView(franceBounds.getCenter(), map.getBoundsZoom(franceBounds));
map.setMaxBounds(worldBounds);
map.options.maxBoundsViscosity = 1.0; // Prevents going past bounds while dragging
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return null;
};
export default MapEvents;
+19 -52
View File
@@ -1,70 +1,37 @@
"use client"; "use client";
import { useState, FormEvent } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import sendMail from "@/lib/sendMail";
import { errorLog } from "@/utils/logger";
import useContactForm from "@/hooks/useContactForm"; import useContactForm from "@/hooks/useContactForm";
import { handleEmailSubmit } from "@/handlers/formHandlers";
import InfoMessage from "@/app/[lang]/components/InfoMessage";
const ContactForm = () => { const ContactForm = () => {
const t = useTranslations("Contact"); const t = useTranslations("Contact");
const { values, handleChange, resetForm } = useContactForm(); const { values, handleChange, resetForm } = useContactForm();
const [isSending, setIsSending] = useState(false);
const [responseMessage, setResponseMessage] = useState({ const [responseMessage, setResponseMessage] = useState({
isSuccessful: false, isSuccessful: false,
message: "", message: "",
}); });
const [isSending, setIsSending] = useState(false);
const clearMessage = () => {
setTimeout(() => {
setResponseMessage({
isSuccessful: false,
message: "",
});
}, 10000);
};
const handleEmailSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
setIsSending(true);
try {
const response = await sendMail(values);
if (response.status === 250) {
setResponseMessage({
isSuccessful: true,
message: t("success"),
});
resetForm();
clearMessage();
setIsSending(false);
}
} catch (error) {
errorLog(error);
setResponseMessage({
isSuccessful: false,
message: t("failure"),
});
clearMessage();
setIsSending(false);
}
};
const infoMessage = (
<p
className={`${
responseMessage.isSuccessful ? "text-green-600" : "text-red-600"
} italic`}
data-test="info-message"
>
{responseMessage.message}
</p>
);
return ( return (
<> <>
<form onSubmit={handleEmailSubmit} className="space-y-8"> <form
onSubmit={(e) =>
handleEmailSubmit(
e,
t,
setIsSending,
setResponseMessage,
values,
resetForm,
)
}
className="space-y-8"
>
<div> <div>
<label <label
htmlFor="email" htmlFor="email"
@@ -127,7 +94,7 @@ const ContactForm = () => {
> >
{isSending ? t("sending") : t("sendButton")} {isSending ? t("sending") : t("sendButton")}
</button> </button>
{infoMessage} <InfoMessage responseMessage={responseMessage} />
</form> </form>
</> </>
); );
+8 -35
View File
@@ -4,22 +4,12 @@ import { TimeControl } from "@/types";
import { useMemo, useRef, useCallback, useEffect } from "react"; import { useMemo, useRef, useCallback, useEffect } from "react";
import L, { LatLngLiteral, Marker, DomUtil } from "leaflet"; import L, { LatLngLiteral, Marker, DomUtil } from "leaflet";
import { MapContainer, TileLayer, LayerGroup } from "react-leaflet";
import MarkerClusterGroup from "react-leaflet-cluster"; import MarkerClusterGroup from "react-leaflet-cluster";
import {
MapContainer,
TileLayer,
LayerGroup,
useMapEvent,
} from "react-leaflet";
import { FaAngleDoubleDown } from "react-icons/fa"; import { FaAngleDoubleDown } from "react-icons/fa";
import { useAtomValue, useSetAtom } from "jotai"; import { useAtomValue, useSetAtom } from "jotai";
import { countBy, groupBy } from "lodash"; import { countBy, groupBy } from "lodash";
import "leaflet/dist/leaflet.css";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet-defaulticon-compatibility";
import "leaflet.smooth_marker_bouncing";
import { import {
mapBoundsAtom, mapBoundsAtom,
debouncedHoveredListTournamentIdAtom, debouncedHoveredListTournamentIdAtom,
@@ -33,6 +23,13 @@ import Legend from "./Legend";
import { TournamentMarker, TournamentMarkerRef } from "./TournamentMarker"; import { TournamentMarker, TournamentMarkerRef } from "./TournamentMarker";
import TimeControlFilters from "./TimeControlFilters"; import TimeControlFilters from "./TimeControlFilters";
import MapEvents from "@/app/[lang]/components/MapEvents";
import "leaflet/dist/leaflet.css";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet-defaulticon-compatibility";
import "leaflet.smooth_marker_bouncing";
// Declare a class type that adds in methods etc. defined by leaflet.smooth_marker_bouncing // Declare a class type that adds in methods etc. defined by leaflet.smooth_marker_bouncing
// to keep Typescript happy // to keep Typescript happy
declare class BouncingMarker extends Marker { declare class BouncingMarker extends Marker {
@@ -46,30 +43,6 @@ declare class BouncingMarker extends Marker {
}; };
} }
const MapEvents = () => {
const setMapBounds = useSetAtom(mapBoundsAtom);
const worldBounds = L.latLngBounds(L.latLng(-90, -180), L.latLng(90, 180));
const franceBounds = L.latLngBounds(
L.latLng(42.08, -5.12),
L.latLng(51.17, 9.53),
);
const map = useMapEvent("moveend", () => {
// Set the map bounds atoms when the user pans/zooms
setMapBounds(map.getBounds());
});
// viewport agnostic centering of France & max world bounds
useEffect(() => {
map.setView(franceBounds.getCenter(), map.getBoundsZoom(franceBounds));
map.setMaxBounds(worldBounds);
map.options.maxBoundsViscosity = 1.0; // Prevents going past bounds while dragging
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return null;
};
const stopBouncingMarkers = () => { const stopBouncingMarkers = () => {
const markers = const markers =
// @ts-ignore // @ts-ignore
+7 -16
View File
@@ -1,22 +1,17 @@
"use client"; "use client";
import dynamic from "next/dynamic"; type TournamentsDisplayProps = {
import { useTranslations } from "next-intl"; tournaments: Tournament[];
import { useHydrateAtoms } from "jotai/utils"; };
import { Tournament } from "@/types"; import { Tournament } from "@/types";
import dynamic from "next/dynamic";
import { useHydrateAtoms } from "jotai/utils";
import { tournamentsAtom } from "@/app/atoms"; import { tournamentsAtom } from "@/app/atoms";
import TournamentTable from "./TournamentTable"; import TournamentTable from "./TournamentTable";
import LoadingMap from "@/app/[lang]/components/LoadingMap";
const LoadingMap = () => {
const t = useTranslations("Tournaments");
return (
<div className="grid h-content place-items-center bg-white text-gray-900 dark:bg-gray-800 dark:text-white">
<p>{t("loading")}</p>
</div>
);
};
/** /**
* Imports the tournament map component, ensuring CSR only. * Imports the tournament map component, ensuring CSR only.
@@ -27,10 +22,6 @@ const TournamentMap = dynamic(() => import("./TournamentMap"), {
loading: LoadingMap, loading: LoadingMap,
}); });
type TournamentsDisplayProps = {
tournaments: Tournament[];
};
export default function TournamentsDisplay({ export default function TournamentsDisplay({
tournaments, tournaments,
}: TournamentsDisplayProps) { }: TournamentsDisplayProps) {
+2 -1
View File
@@ -20,6 +20,7 @@ export interface TournamentData {
norm_tournament: boolean; norm_tournament: boolean;
date: string; date: string;
coordinates: [number, number]; coordinates: [number, number];
pending: boolean;
} }
const tcMap: Record<TournamentData["time_control"], TimeControl> = { const tcMap: Record<TournamentData["time_control"], TimeControl> = {
@@ -110,6 +111,7 @@ const getTournaments = async () => {
timeControl, timeControl,
latLng: { lat: t.coordinates[0], lng: t.coordinates[1] }, latLng: { lat: t.coordinates[0], lng: t.coordinates[1] },
norm: t.norm_tournament, norm: t.norm_tournament,
pending: t.pending,
}; };
}); });
} catch (error) { } catch (error) {
@@ -120,6 +122,5 @@ const getTournaments = async () => {
export default async function Tournaments() { export default async function Tournaments() {
const tournaments = await getTournaments(); const tournaments = await getTournaments();
return <TournamentsDisplay tournaments={tournaments} />; return <TournamentsDisplay tournaments={tournaments} />;
} }
+53
View File
@@ -0,0 +1,53 @@
import clientPromise from "@/lib/mongodb";
import { NextResponse } from "next/server";
import { errorLog } from "@/utils/logger";
export async function POST(req: Request) {
const {
address,
town,
department,
tournament,
url,
time_control,
norm_tournament,
date,
coordinates,
country,
} = await req.json();
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB").collection("tournaments");
const tournamentData = {
address,
town,
department,
tournament,
url,
time_control,
norm_tournament,
date,
coordinates,
country,
entry_method: "manual",
pending: true,
};
const result = await db.insertOne(tournamentData);
if (result.insertedId) {
return new NextResponse(
JSON.stringify({ success: "Tournament added to DB as pending" }),
{ status: 201, headers: { "Content-Type": "application/json" } },
);
}
} catch (error) {
errorLog(error);
return new NextResponse(
JSON.stringify({ error: "Failed to insert tournament data" }),
{ status: 500, headers: { "Content-Type": "application/json" } },
);
}
}
+14 -4
View File
@@ -1,6 +1,6 @@
import { TimeControl, Tournament } from "@/types"; import { TimeControl, Tournament } from "@/types";
import { atom } from "jotai"; import { atom } from "jotai";
import { LatLngBounds } from "leaflet"; import { LatLngBounds, LatLngLiteral } from "leaflet";
import atomWithDebounce from "@/utils/atomWithDebounce"; import atomWithDebounce from "@/utils/atomWithDebounce";
import { normalizedContains } from "@/utils/string"; import { normalizedContains } from "@/utils/string";
@@ -16,6 +16,11 @@ export const rapidAtom = atom(true);
export const blitzAtom = atom(true); export const blitzAtom = atom(true);
export const otherAtom = atom(true); export const otherAtom = atom(true);
export const franceCenterAtom = atom<LatLngLiteral>({
lat: 47.0844,
lng: 2.3964,
});
export const { export const {
currentValueAtom: hoveredMapTournamentGroupIdAtom, currentValueAtom: hoveredMapTournamentGroupIdAtom,
debouncedValueAtom: debouncedHoveredMapTournamentGroupIdAtom, debouncedValueAtom: debouncedHoveredMapTournamentGroupIdAtom,
@@ -34,10 +39,11 @@ export const filteredTournamentsByTimeControlAtom = atom((get) => {
return tournaments.filter( return tournaments.filter(
(tournament) => (tournament) =>
(tournament.timeControl === TimeControl.Classic && classic) || !tournament.pending &&
((tournament.timeControl === TimeControl.Classic && classic) ||
(tournament.timeControl === TimeControl.Rapid && rapid) || (tournament.timeControl === TimeControl.Rapid && rapid) ||
(tournament.timeControl === TimeControl.Blitz && blitz) || (tournament.timeControl === TimeControl.Blitz && blitz) ||
(tournament.timeControl === TimeControl.Other && other), (tournament.timeControl === TimeControl.Other && other)),
); );
}); });
@@ -54,7 +60,11 @@ export const filteredTournamentsListAtom = atom((get) => {
// When searching, we search all the tournament, regardless of the map display // When searching, we search all the tournament, regardless of the map display
if (searchString !== "") { if (searchString !== "") {
return filteredByNorm.filter((t) => normalizedContains(t.town, searchString) || normalizedContains(t.tournament, searchString)); return filteredByNorm.filter(
(t) =>
normalizedContains(t.town, searchString) ||
normalizedContains(t.tournament, searchString),
);
} }
// If we not syncing to the map, return all tournaments // If we not syncing to the map, return all tournaments
+11
View File
@@ -26,6 +26,7 @@ body {
rgb(var(--background-start-rgb)); rgb(var(--background-start-rgb));
} }
/* Search input clear icon */
input[type="search"]::-ms-clear { input[type="search"]::-ms-clear {
display: none; display: none;
width: 0; width: 0;
@@ -42,3 +43,13 @@ input[type="search"]::-webkit-search-results-button,
input[type="search"]::-webkit-search-results-decoration { input[type="search"]::-webkit-search-results-decoration {
display: none; display: none;
} }
/* Remove buttons on number input field */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0
}
input[type=number] {
-moz-appearance: textfield;
}
+84
View File
@@ -0,0 +1,84 @@
import { ResponseMessage, TournamentFormProps } from "@/types";
import { LatLngLiteral } from "leaflet";
import { Dispatch, FormEvent, SetStateAction } from "react";
import { useTranslations } from "next-intl";
import { clearMessage } from "@/app/[lang]/components/InfoMessage";
import { errorLog } from "@/utils/logger";
import sendMail from "@/lib/sendMail";
import tournamentFormToDB from "@/lib/tournamentFormToDB";
import discordWebhook from "@/lib/discordWebhook";
export const handleClearTournamentForm = (
formRefs: TournamentFormProps,
center: LatLngLiteral,
) => {
Object.values(formRefs).forEach((ref) => {
if (ref.current) ref.current.value = "";
});
formRefs.setPosition(center);
};
export const handleTournamentSubmit = async (
e: FormEvent<HTMLFormElement>,
t: ReturnType<typeof useTranslations>,
setIsSending: Dispatch<SetStateAction<boolean>>,
setResponseMessage: Dispatch<SetStateAction<ResponseMessage>>,
formRefs: TournamentFormProps,
) => {
e.preventDefault();
setIsSending(true);
try {
await tournamentFormToDB(formRefs); // write to DB
await discordWebhook(formRefs); // send Discord notification
setIsSending(false);
setResponseMessage({
isSuccessful: true,
message: t("success"),
});
clearMessage(setResponseMessage);
} catch (error) {
errorLog(error);
setResponseMessage({
isSuccessful: false,
message: t("failure"),
});
clearMessage(setResponseMessage);
} finally {
setIsSending(false);
}
};
export const handleEmailSubmit = async (
e: FormEvent<HTMLFormElement>,
t: ReturnType<typeof useTranslations>,
setIsSending: Dispatch<SetStateAction<boolean>>,
setResponseMessage: Dispatch<SetStateAction<ResponseMessage>>,
values: Record<string, string>,
resetForm: () => void,
) => {
e.preventDefault();
setIsSending(true);
try {
const response = await sendMail(values);
if (response.status === 250) {
setResponseMessage({
isSuccessful: true,
message: t("success"),
});
resetForm();
clearMessage(setResponseMessage);
setIsSending(false);
}
} catch (error) {
errorLog(error);
setResponseMessage({
isSuccessful: false,
message: t("failure"),
});
clearMessage(setResponseMessage);
setIsSending(false);
}
};
+42
View File
@@ -0,0 +1,42 @@
import { TournamentFormProps } from "@/types";
import { useRef, useState } from "react";
import { LatLngLiteral } from "leaflet";
import { useAtomValue } from "jotai";
import { franceCenterAtom } from "@/app/atoms";
export const useTournamentForm = (): TournamentFormProps => {
const center = useAtomValue(franceCenterAtom);
const tournamentNameRef = useRef(null);
const dateRef = useRef(null);
const urlRef = useRef(null);
const timeControlRef = useRef(null);
const normRef = useRef(null);
const addressRef = useRef(null);
const townRef = useRef(null);
const departmentRef = useRef(null);
const countryRef = useRef(null);
const yourNameRef = useRef(null);
const yourEmailRef = useRef(null);
const messageRef = useRef(null);
const [position, setPosition] = useState<LatLngLiteral>(center);
return {
tournamentNameRef,
dateRef,
urlRef,
timeControlRef,
normRef,
addressRef,
townRef,
departmentRef,
countryRef,
yourNameRef,
yourEmailRef,
messageRef,
position,
setPosition,
};
};
export default useTournamentForm;
+48
View File
@@ -0,0 +1,48 @@
import { TournamentFormProps } from "@/types";
import formatDate from "@/utils/formatDate";
const discordWebhook = async ({
tournamentNameRef,
countryRef,
dateRef,
timeControlRef,
yourNameRef,
yourEmailRef,
messageRef,
}: TournamentFormProps) => {
const webhookURL = process.env.NEXT_PUBLIC_DISCORD_WEBHOOK;
if (!webhookURL) {
throw new Error("Discord webhook URL is not defined");
}
const webhookBody = {
embeds: [
{
title: "Tournament Submitted",
fields: [
{ name: "Tournament", value: tournamentNameRef.current?.value },
{ name: "Country", value: countryRef.current?.value },
{ name: "Date", value: formatDate(dateRef.current?.value) },
{
name: "Time Control",
value: timeControlRef.current?.value,
},
{ name: "Sender", value: yourNameRef.current?.value },
{ name: "Sender Email", value: yourEmailRef.current?.value },
{ name: "Message", value: messageRef.current?.value },
],
},
],
};
return await fetch(webhookURL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(webhookBody),
});
};
export default discordWebhook;
+28
View File
@@ -0,0 +1,28 @@
import { LatLngLiteral } from "leaflet";
import { TournamentFormProps } from "@/types";
import formatDate from "@/utils/formatDate";
const tournamentFormToDB = async (formRefs: TournamentFormProps) => {
const data = {
address: formRefs.addressRef.current?.value,
town: formRefs.townRef.current?.value.toUpperCase(),
department: formRefs.departmentRef.current?.value,
tournament: formRefs.tournamentNameRef.current?.value,
url: formRefs.urlRef.current?.value,
time_control: formRefs.timeControlRef.current?.value,
date: formatDate(formRefs.dateRef.current?.value),
coordinates: [formRefs.position.lat, formRefs.position.lng],
country: formRefs.countryRef.current?.value,
norm_tournament: formRefs.normRef.current?.value,
};
return await fetch("/api/add-tournament", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
};
export default tournamentFormToDB;
+44
View File
@@ -67,5 +67,49 @@
"sending": "Sending...", "sending": "Sending...",
"success": "Thank you for your message.", "success": "Thank you for your message.",
"failure": "Sorry, something went wrong. Please try again." "failure": "Sorry, something went wrong. Please try again."
},
"AddTournament": {
"title": "Add a Tournament",
"info": "Fill in the form below and your tournament will be reviewed shortly.",
"tournamentNameLabel": "Tournament Name",
"tournamentNamePlaceholder": "Tournament name",
"dateLabel": "Date",
"urlLabel": "URL",
"urlPlaceholder": "www.example.com",
"tcLabel": "Time Control",
"tcOption1": "Classical",
"tcOption2": "Rapid",
"tcOption3": "Blitz",
"tcOption4": "Other",
"normLabel": "Norm Tournament?",
"normNo": "No",
"normYes": "Yes",
"addressLabel": "Address",
"addressPlaceholder": "Address",
"townLabel": "Town",
"townPlaceholder": "Town",
"departmentLabel": "County",
"departmentPlaceholder": "County",
"postcodeLabel": "Postcode",
"postcodePlaceholder": "Postcode",
"countryLabel": "Country",
"countryPlaceholder": "Country",
"yourNameLabel": "Your Name",
"yourNamePlaceholder": "Your Name",
"yourEmailLabel": "Your Email",
"yourEmailPlaceholder": "Your Email",
"messageLabel": "Additional Info / Message",
"messagePlaceholder": "Additional Info / Message",
"sendButton": "Submit Tournament",
"sending": "Sending...",
"clearForm": "Clear Form",
"success": "Thank you for your message.",
"failure": "Sorry, something went wrong. Please try again."
},
"Map": {
"latLabel": "Latitude",
"lngLabel": "Longitude"
} }
} }
+45
View File
@@ -67,5 +67,50 @@
"sending": "Envoi en cours...", "sending": "Envoi en cours...",
"success": "Merci pour votre message.", "success": "Merci pour votre message.",
"failure": "Oops, quelque chose ne va pas. Veuillez réessayer SVP." "failure": "Oops, quelque chose ne va pas. Veuillez réessayer SVP."
},
"AddTournament": {
"title": "Ajouter un Tournoi",
"info": "Veuillez remplir le formulaire ci-dessous et votre tournoi sera validé très prochainement.",
"tournamentNameLabel": "Nom du Tournoi",
"tournamentNamePlaceholder": "Nom du tournoi",
"dateLabel": "Date",
"urlLabel": "URL",
"urlPlaceholder": "www.example.com",
"tcLabel": "Cadence",
"tcOption1": "Cadence Lente",
"tcOption2": "Rapide",
"tcOption3": "Blitz",
"tcOption4": "Autres",
"normLabel": "Tournoi à norme ?",
"normNo": "Non",
"normYes": "Oui",
"addressLabel": "Adresse",
"addressPlaceholder": "Adresse",
"townLabel": "Ville",
"townPlaceholder": "Ville",
"departmentLabel": "Département",
"departmentPlaceholder": "Département",
"postcodeLabel": "Code Postal",
"postcodePlaceholder": "Code Postal",
"countryLabel": "Pays",
"countryPlaceholder": "Pays",
"yourNameLabel": "Votre Nom",
"yourNamePlaceholder": "Votre Nom",
"yourEmailLabel": "Votre adresse mail",
"yourEmailPlaceholder": "Votre adresse mail",
"messageLabel": "Information complémentaire",
"messagePlaceholder": "Additional Info",
"sendButton": "Envoi",
"sending": "Envoi en cours...",
"clearForm": "Réinitialiser",
"success": "Merci pour votre message.",
"failure": "Oops, quelque chose ne va pas. Veuillez réessayer SVP."
},
"Map": {
"latLabel": "Latitude",
"lngLabel": "Longitude"
} }
} }
+30
View File
@@ -1,4 +1,5 @@
import { LatLngLiteral } from "leaflet"; import { LatLngLiteral } from "leaflet";
import { Dispatch, MutableRefObject, SetStateAction } from "react";
export enum TimeControl { export enum TimeControl {
Classic = "Classic", Classic = "Classic",
@@ -18,6 +19,35 @@ export interface Tournament {
date: string; date: string;
latLng: LatLngLiteral; latLng: LatLngLiteral;
norm: boolean; norm: boolean;
pending: boolean;
}
export interface MapProps {
position: LatLngLiteral;
setPosition: Dispatch<SetStateAction<LatLngLiteral>>;
center: LatLngLiteral;
}
export interface TournamentFormProps {
addressRef: MutableRefObject<HTMLInputElement | null>;
townRef: MutableRefObject<HTMLInputElement | null>;
departmentRef: MutableRefObject<HTMLInputElement | null>;
tournamentNameRef: MutableRefObject<HTMLInputElement | null>;
urlRef: MutableRefObject<HTMLInputElement | null>;
timeControlRef: MutableRefObject<HTMLSelectElement | null>;
dateRef: MutableRefObject<HTMLInputElement | null>;
countryRef: MutableRefObject<HTMLInputElement | null>;
normRef: MutableRefObject<HTMLSelectElement | null>;
yourNameRef: MutableRefObject<HTMLInputElement | null>;
yourEmailRef: MutableRefObject<HTMLInputElement | null>;
messageRef: MutableRefObject<HTMLTextAreaElement | null>;
position: LatLngLiteral;
setPosition: Dispatch<SetStateAction<LatLngLiteral>>;
}
export interface ResponseMessage {
isSuccessful: boolean;
message: string;
} }
export type ScrollableElement = Window | HTMLElement; export type ScrollableElement = Window | HTMLElement;
+10
View File
@@ -0,0 +1,10 @@
const formatDate = (inputDate: any) => {
// TODO fix type
const date = new Date(inputDate);
const day = String(date.getDate()).padStart(2, "0");
const month = String(date.getMonth() + 1).padStart(2, "0");
const year = date.getFullYear();
return `${day}/${month}/${year}`;
};
export default formatDate;