mirror of
https://github.com/TheRealOwenRees/echecsfrance.git
synced 2026-07-23 04:26:57 +00:00
Reorganise code - use src folder
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useRef } from "react";
|
||||
|
||||
import { useSetAtom } from "jotai";
|
||||
import L, { LatLngLiteral } from "leaflet";
|
||||
import "leaflet-defaulticon-compatibility";
|
||||
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import { useFormContext, useWatch } from "react-hook-form";
|
||||
import { MapContainer, Marker, TileLayer } from "react-leaflet";
|
||||
|
||||
import { mapBoundsAtom } from "@/atoms";
|
||||
import MapEvents from "@/components/MapEvents";
|
||||
|
||||
const center: LatLngLiteral = { lat: 47.0844, lng: 2.3964 };
|
||||
|
||||
const Map = () => {
|
||||
const { control, setValue } = useFormContext();
|
||||
|
||||
const latValue = useWatch({ control, name: "tournament.coordinates.0" });
|
||||
const lngValue = useWatch({ control, name: "tournament.coordinates.1" });
|
||||
|
||||
const setMapBounds = useSetAtom(mapBoundsAtom);
|
||||
const markerRef = useRef<L.Marker | null>(null);
|
||||
|
||||
const eventHandlers = useMemo(
|
||||
() => ({
|
||||
dragend() {
|
||||
const marker = markerRef.current;
|
||||
if (marker != null) {
|
||||
const position = marker.getLatLng();
|
||||
setValue(
|
||||
"tournament.coordinates.0",
|
||||
Math.round((position.lat + Number.EPSILON) * 10000) / 10000,
|
||||
);
|
||||
setValue(
|
||||
"tournament.coordinates.1",
|
||||
Math.round((position.lng + Number.EPSILON) * 10000) / 10000,
|
||||
);
|
||||
}
|
||||
},
|
||||
}),
|
||||
[setValue],
|
||||
);
|
||||
|
||||
return (
|
||||
<MapContainer
|
||||
center={center}
|
||||
zoom={5}
|
||||
scrollWheelZoom={false}
|
||||
style={{ height: "600px", flexGrow: 1 }}
|
||||
ref={(map) => {
|
||||
if (map) {
|
||||
setMapBounds(map.getBounds());
|
||||
}
|
||||
}}
|
||||
>
|
||||
<MapEvents />
|
||||
<TileLayer
|
||||
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
|
||||
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||
/>
|
||||
<Marker
|
||||
position={{ lat: latValue, lng: lngValue }}
|
||||
draggable={true}
|
||||
ref={markerRef}
|
||||
eventHandlers={eventHandlers}
|
||||
/>
|
||||
</MapContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Map;
|
||||
@@ -0,0 +1,231 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useTranslations } from "next-intl";
|
||||
import dynamic from "next/dynamic";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { clearMessage } from "@/components/InfoMessage";
|
||||
import InfoMessage from "@/components/InfoMessage";
|
||||
import LoadingMap from "@/components/LoadingMap";
|
||||
import { DateField } from "@/components/form/DateField";
|
||||
import { SelectField } from "@/components/form/SelectField";
|
||||
import { SwitchField } from "@/components/form/SwitchField";
|
||||
import { TextAreaField } from "@/components/form/TextAreaField";
|
||||
import { TextField } from "@/components/form/TextField";
|
||||
import { addTournamentSchema } from "@/schemas";
|
||||
import { TimeControl } from "@/types";
|
||||
import { trpc } from "@/utils/trpc";
|
||||
|
||||
type TournamentFormValues = z.infer<typeof addTournamentSchema>;
|
||||
|
||||
const Map = dynamic(() => import("./Map"), {
|
||||
ssr: false,
|
||||
loading: LoadingMap,
|
||||
});
|
||||
|
||||
const TournamentForm = () => {
|
||||
const t = useTranslations("AddTournament");
|
||||
const at = useTranslations("App");
|
||||
const addTournament = trpc.addTournament.useMutation();
|
||||
const [responseMessage, setResponseMessage] = useState({
|
||||
isSuccessful: false,
|
||||
message: "",
|
||||
});
|
||||
|
||||
const form = useForm<TournamentFormValues>({
|
||||
resolver: zodResolver(addTournamentSchema),
|
||||
defaultValues: {
|
||||
tournament: {
|
||||
norm_tournament: false,
|
||||
coordinates: [47.0844, 2.3964],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: TournamentFormValues) => {
|
||||
try {
|
||||
await addTournament.mutateAsync(data);
|
||||
setResponseMessage({
|
||||
isSuccessful: true,
|
||||
message: t("success"),
|
||||
});
|
||||
|
||||
clearMessage(setResponseMessage);
|
||||
form.reset();
|
||||
} catch (err: unknown) {
|
||||
console.log(err);
|
||||
setResponseMessage({
|
||||
isSuccessful: true,
|
||||
message: t("failure"),
|
||||
});
|
||||
|
||||
clearMessage(setResponseMessage);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
||||
<div className="grid grid-cols-4 items-start gap-6">
|
||||
<div className="col-span-4">
|
||||
<TextField
|
||||
name="tournament.tournament"
|
||||
control={form.control}
|
||||
label={t("tournamentNameLabel")}
|
||||
placeholder={t("tournamentNamePlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<DateField
|
||||
name="tournament.date"
|
||||
control={form.control}
|
||||
label={t("dateLabel")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<TextField
|
||||
name="tournament.url"
|
||||
control={form.control}
|
||||
label={t("urlLabel")}
|
||||
placeholder={t("urlPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<SelectField
|
||||
name="tournament.time_control"
|
||||
control={form.control}
|
||||
label={t("tcLabel")}
|
||||
options={[
|
||||
TimeControl.Classic,
|
||||
TimeControl.Rapid,
|
||||
TimeControl.Blitz,
|
||||
].map((tc) => ({
|
||||
value: tc,
|
||||
label: at("timeControlEnum", { tc }),
|
||||
}))}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<SwitchField
|
||||
name="tournament.norm_tournament"
|
||||
control={form.control}
|
||||
label={t("normLabel")}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-4">
|
||||
<TextField
|
||||
name="tournament.address"
|
||||
control={form.control}
|
||||
label={t("addressLabel")}
|
||||
placeholder={t("addressPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-4 sm:col-span-2">
|
||||
<TextField
|
||||
name="tournament.town"
|
||||
control={form.control}
|
||||
label={t("townLabel")}
|
||||
placeholder={t("townPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<TextField
|
||||
name="tournament.department"
|
||||
control={form.control}
|
||||
label={t("departmentLabel")}
|
||||
placeholder={t("departmentPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<TextField
|
||||
name="tournament.country"
|
||||
control={form.control}
|
||||
label={t("countryLabel")}
|
||||
placeholder={t("countryPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<TextField
|
||||
name="name"
|
||||
control={form.control}
|
||||
label={t("yourNameLabel")}
|
||||
placeholder={t("yourNamePlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<TextField
|
||||
name="email"
|
||||
control={form.control}
|
||||
label={t("yourEmailLabel")}
|
||||
placeholder={t("yourEmailPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-4 row-span-2 sm:col-span-2">
|
||||
<TextAreaField
|
||||
name="message"
|
||||
control={form.control}
|
||||
label={t("messageLabel")}
|
||||
rows={6}
|
||||
placeholder={t("messagePlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<TextField
|
||||
name="tournament.coordinates.0"
|
||||
control={form.control}
|
||||
label={t("latLabel")}
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 sm:col-span-1">
|
||||
<TextField
|
||||
name="tournament.coordinates.1"
|
||||
control={form.control}
|
||||
label={t("lngLabel")}
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<section id="map" className="z-0 col-span-4 flex h-auto">
|
||||
<Map />
|
||||
</section>
|
||||
</div>
|
||||
<button
|
||||
disabled={form.formState.isSubmitting}
|
||||
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"
|
||||
>
|
||||
{form.formState.isSubmitting ? t("sending") : t("sendButton")}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => form.reset()}
|
||||
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>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default TournamentForm;
|
||||
@@ -0,0 +1,26 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import L, { LatLngLiteral } from "leaflet";
|
||||
import "leaflet-defaulticon-compatibility";
|
||||
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
|
||||
import "leaflet.smooth_marker_bouncing";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import { countBy, groupBy } from "lodash";
|
||||
|
||||
import { clubsAtom } from "@/atoms";
|
||||
import { Map, MapMarker } from "@/components/Map";
|
||||
|
||||
import { ClubMarker } from "./ClubMarker";
|
||||
|
||||
const ClubMap = () => {
|
||||
const clubs = useAtomValue(clubsAtom);
|
||||
|
||||
const markers: MapMarker[] = useMemo(
|
||||
() =>
|
||||
clubs.map((club) => {
|
||||
return {
|
||||
markerId: club.id,
|
||||
tableIds: [club.id],
|
||||
component: <ClubMarker key={club.id} club={club} />,
|
||||
};
|
||||
}),
|
||||
[clubs],
|
||||
);
|
||||
|
||||
return <Map markers={markers} />;
|
||||
};
|
||||
|
||||
export default ClubMap;
|
||||
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { forwardRef, useImperativeHandle, useMemo, useRef } from "react";
|
||||
|
||||
import { useSetAtom } from "jotai";
|
||||
import L from "leaflet";
|
||||
import { Marker, MarkerProps, Popup } from "react-leaflet";
|
||||
|
||||
import { debouncedHoveredMapIdAtom } from "@/atoms";
|
||||
import type { MarkerRef } from "@/components/Map";
|
||||
import { TimeControlColours } from "@/constants";
|
||||
import type { BouncingMarker } from "@/leafletTypes";
|
||||
import { Club } from "@/types";
|
||||
|
||||
type ClubMarkerProps = {
|
||||
club: Club;
|
||||
} & Omit<MarkerProps, "position">;
|
||||
|
||||
export const ClubMarker = forwardRef<MarkerRef, ClubMarkerProps>(
|
||||
({ club, ...markerProps }, ref) => {
|
||||
const markerRef = useRef<L.Marker<any> | null>(null);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
getMarker: () => markerRef.current!,
|
||||
bounce: () => {
|
||||
const bouncingMarker = markerRef.current as BouncingMarker;
|
||||
bouncingMarker.setBouncingOptions({ contractHeight: 0 });
|
||||
bouncingMarker.bounce();
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const { id, latLng } = club;
|
||||
|
||||
const setHoveredMapId = useSetAtom(debouncedHoveredMapIdAtom);
|
||||
|
||||
const iconOptions = useMemo(
|
||||
() =>
|
||||
new L.DivIcon({
|
||||
html: `
|
||||
<svg x="0px" y="0px" viewBox="0 0 365 560" enable-background="new 0 0 365 560" xml:space="preserve">
|
||||
<g><circle fill="#FFFFFF" cx="182" cy="180" r="70" /></g>
|
||||
<g><path stroke="#666666" stroke-width="10" fill="${TimeControlColours.Classic}" d="M182.9,551.7c0,0.1,0.2,0.3,0.2,0.3S358.3,283,358.3,194.6c0-130.1-88.8-186.7-175.4-186.9 C96.3,7.9,7.5,64.5,7.5,194.6c0,88.4,175.3,357.4,175.3,357.4S182.9,551.7,182.9,551.7z M122.2,187.2c0-33.6,27.2-60.8,60.8-60.8 c33.6,0,60.8,27.2,60.8,60.8S216.5,248,182.9,248C149.4,248,122.2,220.8,122.2,187.2z"/></g>
|
||||
</svg>
|
||||
`,
|
||||
className: "",
|
||||
iconSize: [24, 40],
|
||||
iconAnchor: [12, 40],
|
||||
popupAnchor: [1, -40],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<Marker
|
||||
ref={markerRef}
|
||||
position={latLng}
|
||||
icon={iconOptions}
|
||||
eventHandlers={{
|
||||
mouseover: () => setHoveredMapId(id),
|
||||
mouseout: () => setHoveredMapId(null),
|
||||
}}
|
||||
{...markerProps}
|
||||
>
|
||||
<Popup maxWidth={10000}>
|
||||
<div className="flex max-w-[calc(100vw-80px)] flex-col gap-3 lg:max-w-[calc(100vw/2-80px)]">
|
||||
<div className="flex flex-col gap-0">
|
||||
<div>{club.name}</div>
|
||||
{club.address && <div>{club.address}</div>}
|
||||
{club.website && (
|
||||
<div>
|
||||
<a
|
||||
href={club.website}
|
||||
className="text-primary hover:text-primary-800"
|
||||
target="_blank"
|
||||
>
|
||||
{club.website}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{club.url && (
|
||||
<div>
|
||||
<a
|
||||
href={club.url}
|
||||
className="text-primary hover:text-primary-800"
|
||||
target="_blank"
|
||||
>
|
||||
{club.url}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{club.email && (
|
||||
<div>
|
||||
<a
|
||||
href={`mailto:${club.email}`}
|
||||
className="text-primary hover:text-primary-800"
|
||||
>
|
||||
{club.email}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Popup>
|
||||
</Marker>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ClubMarker.displayName = "ClubMarker";
|
||||
@@ -0,0 +1,148 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useAtom, useAtomValue, useSetAtom } from "jotai";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { FaExternalLinkAlt } from "react-icons/fa";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import {
|
||||
debouncedHoveredListIdAtom,
|
||||
debouncedHoveredMapIdAtom,
|
||||
filteredClubsListAtom,
|
||||
hoveredMapIdAtom,
|
||||
syncVisibleAtom,
|
||||
} from "@/atoms";
|
||||
import ScrollToTopButton from "@/components/ScrollToTopButton";
|
||||
import SearchBar from "@/components/SearchBar";
|
||||
import { useBreakpoint } from "@/hooks/tailwind";
|
||||
|
||||
const ClubTable = () => {
|
||||
const t = useTranslations("Clubs");
|
||||
const at = useTranslations("App");
|
||||
|
||||
const filteredClubs = useAtomValue(filteredClubsListAtom);
|
||||
const [syncVisible, setSyncVisible] = useAtom(syncVisibleAtom);
|
||||
const hoveredMapId = useAtomValue(hoveredMapIdAtom);
|
||||
const debouncedHoveredMapId = useAtomValue(debouncedHoveredMapIdAtom);
|
||||
const setHoveredListId = useSetAtom(debouncedHoveredListIdAtom);
|
||||
|
||||
const isLg = useBreakpoint("lg");
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLg || debouncedHoveredMapId === null) return;
|
||||
const clubRow = document.querySelector(
|
||||
`[data-group-id="${debouncedHoveredMapId}"]`,
|
||||
);
|
||||
|
||||
clubRow?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [debouncedHoveredMapId, isLg]);
|
||||
|
||||
return (
|
||||
<section
|
||||
className="club-table grid w-full auto-rows-max pb-20 lg:col-start-2 lg:col-end-3 lg:h-content lg:overflow-y-scroll lg:pb-0"
|
||||
id="listing"
|
||||
>
|
||||
<div className="z-10 flex w-full flex-wrap items-center justify-between gap-3 p-3">
|
||||
<SearchBar />
|
||||
|
||||
<div className="flex flex-col gap-0 text-gray-900 dark:text-white">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mr-2 h-4 w-4 rounded border-gray-400 text-primary focus:ring-primary"
|
||||
checked={syncVisible}
|
||||
onChange={() => setSyncVisible(!syncVisible)}
|
||||
/>
|
||||
{t("syncWithMapCheckbox")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ScrollToTopButton />
|
||||
|
||||
<div className="overflow-x-scroll bg-red-50">
|
||||
<table className="relative min-w-full table-fixed text-center text-xs lg:min-w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="sticky top-0 bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("name")}
|
||||
</th>
|
||||
<th className="sticky top-0 bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("contact")}
|
||||
</th>
|
||||
<th className="sticky top-0 w-[50px] bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("ffe")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{filteredClubs.length === 0 ? (
|
||||
<tr className="bg-white text-gray-900 dark:bg-gray-800 dark:text-white">
|
||||
<td colSpan={4} className="p-3">
|
||||
{t("noneFound")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredClubs.map((club) => (
|
||||
<tr
|
||||
key={club.id}
|
||||
id={club.id}
|
||||
onMouseEnter={() => setHoveredListId(club.id)}
|
||||
onMouseLeave={() => setHoveredListId(null)}
|
||||
className={twMerge(
|
||||
"scroll-m-20 bg-white text-gray-900 hover:bg-gray-200 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-900",
|
||||
hoveredMapId === club.id && "bg-gray-200 dark:bg-gray-900",
|
||||
)}
|
||||
>
|
||||
<td className="px-1 py-2 sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
{club.name}
|
||||
</td>
|
||||
<td className="px-1 py-2 text-left sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
{club.address && <div>{club.address}</div>}
|
||||
{club.website && (
|
||||
<div>
|
||||
<a
|
||||
href={club.website}
|
||||
className="text-primary hover:text-primary-800"
|
||||
target="_blank"
|
||||
>
|
||||
{club.website}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{club.email && (
|
||||
<div>
|
||||
<a
|
||||
href={`mailto:${club.email}`}
|
||||
className="text-primary hover:text-primary-800"
|
||||
>
|
||||
{club.email}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-1 py-2 sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
<div className="flex justify-center">
|
||||
<a
|
||||
href={club.url}
|
||||
target="_blank"
|
||||
className="text-primary hover:text-primary-800"
|
||||
>
|
||||
<FaExternalLinkAlt />
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default ClubTable;
|
||||
@@ -0,0 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import { useHydrateAtoms } from "jotai/utils";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
import { clubsAtom } from "@/atoms";
|
||||
import LoadingMap from "@/components/LoadingMap";
|
||||
import { Club } from "@/types";
|
||||
|
||||
import ClubTable from "./ClubTable";
|
||||
|
||||
type ClubsDisplayProps = {
|
||||
clubs: Club[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Imports the club map component, ensuring CSR only.
|
||||
* @remarks SSR is not supported by react-leaflet
|
||||
*/
|
||||
const ClubMap = dynamic(() => import("./ClubMap"), {
|
||||
ssr: false,
|
||||
loading: LoadingMap,
|
||||
});
|
||||
|
||||
export default function ClubsDisplay({ clubs }: ClubsDisplayProps) {
|
||||
useHydrateAtoms([[clubsAtom, clubs]]);
|
||||
|
||||
return (
|
||||
<main className="relative grid h-full w-full lg:grid-cols-2">
|
||||
<div>
|
||||
<ClubMap />
|
||||
</div>
|
||||
<div className="relative bg-white dark:bg-gray-800 lg:overflow-y-auto">
|
||||
<ClubTable />
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { groupBy } from "lodash";
|
||||
|
||||
import clientPromise from "@/lib/mongodb";
|
||||
import { Club, ClubData } from "@/types";
|
||||
import { errorLog } from "@/utils/logger";
|
||||
|
||||
import ClubsDisplay from "./ClubsDisplay";
|
||||
|
||||
export const revalidate = 3600; // Revalidate cache every 6 hours
|
||||
|
||||
const getClubs = async () => {
|
||||
try {
|
||||
const client = await clientPromise;
|
||||
const db = client.db("tournamentsFranceDB");
|
||||
const data = await db
|
||||
.collection("clubs")
|
||||
.find<ClubData>({})
|
||||
.sort({ name: 1 })
|
||||
.toArray();
|
||||
|
||||
return data
|
||||
.filter((c) => !!c.coordinates)
|
||||
.map<Club>((club) => {
|
||||
return {
|
||||
id: club._id.toString(),
|
||||
name: club.name,
|
||||
url: club.url,
|
||||
address: club.address,
|
||||
email: club.email,
|
||||
website: club.website,
|
||||
latLng: { lat: club.coordinates[0], lng: club.coordinates[1] },
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
errorLog(error);
|
||||
throw new Error("Error fetching club data");
|
||||
}
|
||||
};
|
||||
|
||||
export default async function Clubs() {
|
||||
const clubs = await getClubs();
|
||||
return <ClubsDisplay clubs={clubs} />;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { FaGithub, FaRegEnvelope } from "react-icons/fa";
|
||||
|
||||
import { Link, usePathname } from "@/utils/navigation";
|
||||
|
||||
import ThemeSwitcher from "./ThemeSwitcher";
|
||||
|
||||
export default function Footer() {
|
||||
const t = useTranslations("Footer");
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<footer
|
||||
className="fixed bottom-0 z-30 flex h-12 w-[100vw] flex-col items-center justify-center justify-items-center bg-primary-600 px-5 py-2 text-white dark:bg-gray-700"
|
||||
data-test="footer"
|
||||
>
|
||||
<div className="flex items-center py-2 hover:[&_a]:opacity-80">
|
||||
<a
|
||||
href="https://github.com/TheRealOwenRees/echecsfrance"
|
||||
target="_blank"
|
||||
aria-label={t("githubAria")}
|
||||
className="mr-4"
|
||||
>
|
||||
<FaGithub />
|
||||
</a>
|
||||
<Link href="/contact-us" aria-label={t("contactAria")} className="mr-4">
|
||||
<FaRegEnvelope />
|
||||
</Link>
|
||||
<div className="mr-4 space-x-2 text-xs">
|
||||
<Link href={pathname} locale="fr">
|
||||
FR
|
||||
</Link>
|
||||
<span>|</span>
|
||||
<Link href={pathname} locale="en">
|
||||
EN
|
||||
</Link>
|
||||
</div>
|
||||
<div className="text-xs hover:opacity-80">
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { useAtom } from "jotai";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { burgerMenuIsOpenAtom } from "@/atoms";
|
||||
|
||||
import HamburgerMenu from "./HamburgerMenu";
|
||||
|
||||
const Hamburger = () => {
|
||||
const [burgerMenuIsOpen, setBurgerMenuIsOpen] = useAtom(burgerMenuIsOpenAtom);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="hamburger-button relative z-[99999] space-y-2"
|
||||
data-test="hamburger-button"
|
||||
onClick={() => setBurgerMenuIsOpen(!burgerMenuIsOpen)}
|
||||
>
|
||||
<div
|
||||
className={twMerge(
|
||||
"h-0.5 w-8 bg-gray-600 transition-all duration-300 ease-in-out dark:bg-white",
|
||||
burgerMenuIsOpen &&
|
||||
"translate-x-[1px] translate-y-2.5 rotate-45 bg-white",
|
||||
)}
|
||||
></div>
|
||||
<div
|
||||
className={twMerge(
|
||||
"h-0.5 w-8 bg-gray-600 transition-transform duration-300 ease-linear dark:bg-white",
|
||||
burgerMenuIsOpen && "scale-0 bg-white opacity-0",
|
||||
)}
|
||||
></div>
|
||||
<div
|
||||
className={twMerge(
|
||||
"h-0.5 w-8 bg-gray-600 transition-transform duration-300 ease-in-out dark:bg-white",
|
||||
burgerMenuIsOpen && "-translate-y-2.5 -rotate-45 bg-white",
|
||||
)}
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<HamburgerMenu />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Hamburger;
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Dispatch, RefObject, SetStateAction, useRef, useState } from "react";
|
||||
|
||||
import { useAtom } from "jotai";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { burgerMenuIsOpenAtom } from "@/atoms";
|
||||
import { Link } from "@/utils/navigation";
|
||||
|
||||
const HamburgerMenu = () => {
|
||||
const t = useTranslations("Nav");
|
||||
const [burgerMenuIsOpen, setBurgerMenuIsOpen] = useAtom(burgerMenuIsOpenAtom);
|
||||
|
||||
const closeMenu = () => setBurgerMenuIsOpen(false);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={twMerge(
|
||||
"fixed right-0 top-0 z-[9999] h-[calc(100svh-3rem)] w-full",
|
||||
"flex items-center justify-center bg-primary-600 transition-transform duration-200 ease-linear dark:bg-gray-600 md:hidden",
|
||||
!burgerMenuIsOpen && "translate-x-full",
|
||||
)}
|
||||
>
|
||||
<ul className="list-reset text-white">
|
||||
<li className="py-5 text-center text-xl">
|
||||
<Link
|
||||
onClick={closeMenu}
|
||||
href="/tournaments"
|
||||
className="border-b-2 border-transparent transition-all duration-300 ease-in-out hover:border-white"
|
||||
>
|
||||
{t("tournaments")}
|
||||
</Link>
|
||||
</li>
|
||||
|
||||
<li className="py-5 text-center text-xl">
|
||||
<Link
|
||||
onClick={closeMenu}
|
||||
href="/clubs"
|
||||
className="border-b-2 border-transparent transition-all duration-300 ease-in-out hover:border-white"
|
||||
>
|
||||
{t("clubs")}
|
||||
</Link>
|
||||
</li>
|
||||
|
||||
<li className="py-5 text-center text-xl">
|
||||
<Link
|
||||
onClick={closeMenu}
|
||||
href="/elo"
|
||||
className="border-b-2 border-transparent transition-all duration-300 ease-in-out hover:border-white"
|
||||
>
|
||||
{t("elo")}
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default HamburgerMenu;
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import { Link } from "@/utils/navigation";
|
||||
|
||||
import Hamburger from "./Hamburger";
|
||||
|
||||
export default function Navbar() {
|
||||
const t = useTranslations("Nav");
|
||||
|
||||
const links = [
|
||||
{ title: t("tournaments"), route: "/tournaments" },
|
||||
{ title: t("clubs"), route: "/clubs" },
|
||||
{ title: t("elo"), route: "/elo" },
|
||||
] as const;
|
||||
|
||||
return (
|
||||
<nav
|
||||
className="relative mt-0 h-16 w-full overflow-x-clip border-b-[1px] bg-white px-5 dark:border-gray-700 dark:bg-gray-800"
|
||||
data-test="navbar"
|
||||
>
|
||||
<div className="container mx-auto flex h-full items-center justify-between">
|
||||
<Link
|
||||
className="font-extrabold text-gray-900 no-underline hover:no-underline dark:text-white"
|
||||
href="/"
|
||||
>
|
||||
<span className="font-title text-2xl text-gray-800 dark:text-white">
|
||||
{t("title")}
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
<div className="md:hidden" data-test="mobile-menu">
|
||||
<Hamburger />
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="hidden h-full justify-center md:flex md:w-1/2 md:justify-end"
|
||||
data-test="desktop-menu"
|
||||
>
|
||||
<ul className="list-reset flex h-full flex-1 items-center gap-14 text-gray-900 no-underline dark:text-white md:flex-none">
|
||||
{links.map(({ title, route }) => (
|
||||
<li key={route} className="h-full">
|
||||
<Link
|
||||
className="inline-flex h-full items-center border-b-4 border-t-4 border-transparent transition-all duration-300 ease-in-out hover:border-b-primary-600"
|
||||
href={route}
|
||||
>
|
||||
{title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import useDarkMode from "@/hooks/useDarkMode";
|
||||
|
||||
const ThemeSwitcher = () => {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [colorTheme, setTheme] = useDarkMode();
|
||||
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
if (!mounted) return null;
|
||||
|
||||
return (
|
||||
<div className="cursor-pointer">
|
||||
{colorTheme === "light" ? (
|
||||
<div data-test="toggle-dark" onClick={() => setTheme("light")}>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className="inline-block h-4 w-4"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M9.528 1.718a.75.75 0 01.162.819A8.97 8.97 0 009 6a9 9 0 009 9 8.97 8.97 0 003.463-.69.75.75 0 01.981.98 10.503 10.503 0 01-9.694 6.46c-5.799 0-10.5-4.701-10.5-10.5 0-4.368 2.667-8.112 6.46-9.694a.75.75 0 01.818.162z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
) : (
|
||||
<div data-test="toggle" onClick={() => setTheme("dark")}>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className="inline-block h-4 w-4"
|
||||
>
|
||||
<path d="M12 2.25a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0V3a.75.75 0 01.75-.75zM7.5 12a4.5 4.5 0 119 0 4.5 4.5 0 01-9 0zM18.894 6.166a.75.75 0 00-1.06-1.06l-1.591 1.59a.75.75 0 101.06 1.061l1.591-1.59zM21.75 12a.75.75 0 01-.75.75h-2.25a.75.75 0 010-1.5H21a.75.75 0 01.75.75zM17.834 18.894a.75.75 0 001.06-1.06l-1.59-1.591a.75.75 0 10-1.061 1.06l1.59 1.591zM12 18a.75.75 0 01.75.75V21a.75.75 0 01-1.5 0v-2.25A.75.75 0 0112 18zM7.758 17.303a.75.75 0 00-1.061-1.06l-1.591 1.59a.75.75 0 001.06 1.061l1.591-1.59zM6 12a.75.75 0 01-.75.75H3a.75.75 0 010-1.5h2.25A.75.75 0 016 12zM6.697 7.757a.75.75 0 001.06-1.06l-1.59-1.591a.75.75 0 00-1.061 1.06l1.59 1.591z" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ThemeSwitcher;
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import InfoMessage from "@/components/InfoMessage";
|
||||
import { clearMessage } from "@/components/InfoMessage";
|
||||
import { TextAreaField } from "@/components/form/TextAreaField";
|
||||
import { TextField } from "@/components/form/TextField";
|
||||
import { contactUsSchema } from "@/schemas";
|
||||
import { trpc } from "@/utils/trpc";
|
||||
|
||||
type TournamentFormValues = z.infer<typeof contactUsSchema>;
|
||||
|
||||
const ContactForm = () => {
|
||||
const t = useTranslations("Contact");
|
||||
|
||||
const contactUs = trpc.contactUs.useMutation();
|
||||
const [responseMessage, setResponseMessage] = useState({
|
||||
isSuccessful: false,
|
||||
message: "",
|
||||
});
|
||||
|
||||
const form = useForm<TournamentFormValues>({
|
||||
resolver: zodResolver(contactUsSchema),
|
||||
});
|
||||
|
||||
const onSubmit = async (data: TournamentFormValues) => {
|
||||
try {
|
||||
await contactUs.mutateAsync(data);
|
||||
setResponseMessage({
|
||||
isSuccessful: true,
|
||||
message: t("success"),
|
||||
});
|
||||
|
||||
clearMessage(setResponseMessage);
|
||||
form.reset();
|
||||
} catch (err: unknown) {
|
||||
console.log(err);
|
||||
setResponseMessage({
|
||||
isSuccessful: true,
|
||||
message: t("failure"),
|
||||
});
|
||||
|
||||
clearMessage(setResponseMessage);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
||||
<TextField
|
||||
name="email"
|
||||
control={form.control}
|
||||
label={t("emailLabel")}
|
||||
placeholder={t("emailPlaceholder")}
|
||||
required
|
||||
/>
|
||||
|
||||
<TextField
|
||||
name="subject"
|
||||
control={form.control}
|
||||
label={t("subjectLabel")}
|
||||
placeholder={t("subjectPlaceholder")}
|
||||
required
|
||||
/>
|
||||
|
||||
<TextAreaField
|
||||
name="message"
|
||||
control={form.control}
|
||||
rows={6}
|
||||
label={t("messageLabel")}
|
||||
placeholder={t("messagePlaceholder")}
|
||||
required
|
||||
/>
|
||||
|
||||
<button
|
||||
disabled={form.formState.isSubmitting}
|
||||
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"
|
||||
>
|
||||
{form.formState.isSubmitting ? t("sending") : t("sendButton")}
|
||||
</button>
|
||||
|
||||
<InfoMessage responseMessage={responseMessage} />
|
||||
</form>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactForm;
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import ContactForm from "./ContactForm";
|
||||
|
||||
export default function Contact() {
|
||||
const t = useTranslations("Contact");
|
||||
|
||||
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>
|
||||
<ContactForm />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Disclosure } from "@headlessui/react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { IoChevronForward } from "react-icons/io5";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type KFactorProps = {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export const KFactor = ({ className }: KFactorProps) => {
|
||||
const t = useTranslations("Elo");
|
||||
|
||||
return (
|
||||
<Disclosure>
|
||||
<Disclosure.Button
|
||||
className={twMerge(
|
||||
"flex items-center text-sm text-gray-500 dark:text-neutral-400",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<IoChevronForward className="mr-2 h-4 w-4 transition-transform ui-open:rotate-90 ui-open:transform" />
|
||||
{t("kFactorTitle")}
|
||||
</Disclosure.Button>
|
||||
|
||||
<Disclosure.Panel className="mt-4">
|
||||
<p className="text-sm text-gray-500 dark:text-neutral-400">
|
||||
{t("kFactorInfo1")}
|
||||
</p>
|
||||
<p className="mt-4 text-sm text-gray-500 dark:text-neutral-400">
|
||||
{t("kFactorInfo2")}
|
||||
</p>
|
||||
|
||||
<ul className="mb-8 ml-4 mt-3 list-outside list-disc">
|
||||
{(
|
||||
[
|
||||
"kFactorInfo3",
|
||||
"kFactorInfo4",
|
||||
"kFactorInfo5",
|
||||
"kFactorInfo6",
|
||||
"kFactorInfo7",
|
||||
] as const
|
||||
).map((key) => (
|
||||
<li
|
||||
key={key}
|
||||
className="mt-2 text-sm text-gray-500 dark:text-neutral-400"
|
||||
>
|
||||
{t.rich(key, { b: (str) => <b>{str}</b> })}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Disclosure.Panel>
|
||||
</Disclosure>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,241 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { last } from "lodash";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { FormProvider, useFieldArray, useForm } from "react-hook-form";
|
||||
import { IoAdd, IoCloseOutline } from "react-icons/io5";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { z } from "zod";
|
||||
|
||||
import { RadioGroupField } from "@/components/form/RadioGroupField";
|
||||
import { SelectField } from "@/components/form/SelectField";
|
||||
import { TextField } from "@/components/form/TextField";
|
||||
import { getNewRating } from "@/utils/eloCalculator";
|
||||
|
||||
import { KFactor } from "./KFactor";
|
||||
|
||||
const resultsSchema = z.object({
|
||||
currentElo: z.number().int().positive(),
|
||||
kFactor: z.enum(["40", "30", "20", "15", "10"]),
|
||||
games: z.array(
|
||||
z.object({
|
||||
opponentElo: z.number().int().positive(),
|
||||
result: z.enum(["win", "draw", "loss"]),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
type DeepPartial<T> = T extends object
|
||||
? {
|
||||
[P in keyof T]?: DeepPartial<T[P]>;
|
||||
}
|
||||
: T;
|
||||
|
||||
type EloFormValues = DeepPartial<z.infer<typeof resultsSchema>>;
|
||||
|
||||
export const ManualEloForm = () => {
|
||||
const t = useTranslations("Elo");
|
||||
|
||||
const form = useForm<EloFormValues>({
|
||||
resolver: zodResolver(resultsSchema),
|
||||
defaultValues: {
|
||||
kFactor: "20",
|
||||
games: [{}],
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
fields: gameFields,
|
||||
append: appendGame,
|
||||
remove: removeGame,
|
||||
} = useFieldArray({
|
||||
control: form.control,
|
||||
name: "games",
|
||||
});
|
||||
|
||||
const onSubmit = async (data: EloFormValues) => {};
|
||||
|
||||
const [currentElo, kFactor, games] = form.watch([
|
||||
"currentElo",
|
||||
"kFactor",
|
||||
"games",
|
||||
]);
|
||||
|
||||
type Deltas = {
|
||||
rating: number;
|
||||
deltas: { rating: number; delta: number | undefined }[];
|
||||
};
|
||||
|
||||
const calculations = !Number.isNaN(currentElo)
|
||||
? (games ?? []).reduce<Deltas>(
|
||||
(acc, game) => {
|
||||
if (!Number.isNaN(game?.opponentElo) && game?.result) {
|
||||
const result =
|
||||
game?.result === "win" ? 1 : game?.result === "loss" ? 0 : 0.5;
|
||||
|
||||
const { delta } = getNewRating(
|
||||
currentElo!,
|
||||
game.opponentElo!,
|
||||
result,
|
||||
parseInt(kFactor!, 10),
|
||||
);
|
||||
return {
|
||||
rating: acc.rating + delta,
|
||||
deltas: [...acc.deltas, { rating: acc.rating + delta, delta }],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
rating: acc.rating,
|
||||
deltas: [...acc.deltas, { rating: acc.rating, delta: undefined }],
|
||||
};
|
||||
},
|
||||
{ rating: currentElo!, deltas: [] },
|
||||
)
|
||||
: { rating: currentElo!, deltas: [] };
|
||||
|
||||
const deltas = calculations.deltas;
|
||||
const hasDeltas = deltas.some((d) => d.delta !== undefined);
|
||||
const totalDelta = Math.round(
|
||||
deltas.reduce((acc, delta) => acc + (delta.delta ?? 0), 0),
|
||||
);
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="grid w-full grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<TextField
|
||||
name="currentElo"
|
||||
control={form.control}
|
||||
label={t("currentEloLabel")}
|
||||
placeholder={t("currentEloPlaceholder")}
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
|
||||
<SelectField
|
||||
name="kFactor"
|
||||
control={form.control}
|
||||
label={t("yourKFactorLabel")}
|
||||
options={["40", "20", "10"].map((k) => ({
|
||||
value: k,
|
||||
label: k,
|
||||
}))}
|
||||
isClearable={false}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<KFactor className="mt-2" />
|
||||
|
||||
<h3 className="my-4 text-lg text-gray-900 dark:text-white">
|
||||
{t("resultsTitle")}
|
||||
</h3>
|
||||
|
||||
<div className="flex w-full flex-col gap-6 sm:gap-2">
|
||||
{gameFields.map((game, i) => {
|
||||
return (
|
||||
<div key={i} className="flex w-full flex-col">
|
||||
<div key={i} className="flex w-full items-center space-x-2">
|
||||
<div className="grid w-full grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<TextField
|
||||
name={`games.${i}.opponentElo`}
|
||||
control={form.control}
|
||||
placeholder={t("opponentEloPlaceholder")}
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupField
|
||||
name={`games.${i}.result`}
|
||||
control={form.control}
|
||||
options={["win", "draw", "loss"].map((result) => ({
|
||||
value: result,
|
||||
label: t("gameResult", { result }),
|
||||
}))}
|
||||
required
|
||||
/>
|
||||
{gameFields.length > 1 && (
|
||||
<button
|
||||
className="hidden h-8 w-8 items-center justify-center rounded-md bg-neutral-100 hover:bg-neutral-200 dark:bg-neutral-600 dark:hover:bg-neutral-700 sm:flex"
|
||||
type="button"
|
||||
onClick={() => removeGame(i)}
|
||||
>
|
||||
<IoCloseOutline className="h-6 w-6 text-gray-900 transition-all duration-200 hover:text-primary dark:text-neutral-400 hover:dark:text-white" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{gameFields.length > 1 && (
|
||||
<button
|
||||
className="flex h-8 w-8 items-center justify-center rounded-md bg-neutral-100 hover:bg-neutral-200 dark:bg-neutral-600 dark:hover:bg-neutral-700 sm:hidden"
|
||||
type="button"
|
||||
onClick={() => removeGame(i)}
|
||||
>
|
||||
<IoCloseOutline className="h-6 w-6 text-gray-900 transition-all duration-200 hover:text-primary dark:text-neutral-400 hover:dark:text-white" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{deltas[i]?.delta !== undefined && (
|
||||
<div
|
||||
className={twMerge(
|
||||
"mt-2 flex justify-end text-gray-900 dark:text-neutral-400",
|
||||
gameFields.length > 1 && "mr-10",
|
||||
i === deltas.length - 1 && "font-bold",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={twMerge(
|
||||
deltas[i].delta! > 0 && "text-success",
|
||||
deltas[i].delta! < 0 && "text-error",
|
||||
)}
|
||||
>
|
||||
{deltas[i]!.delta! >= 0 ? "+" : ""}
|
||||
{deltas[i].delta!}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{hasDeltas && (
|
||||
<div className="mt-8 text-right text-lg font-bold text-gray-900 dark:text-neutral-400">
|
||||
{t.rich("finalRating", {
|
||||
rating: Math.round(last(deltas)!.rating),
|
||||
delta: () => (
|
||||
<span
|
||||
className={twMerge(
|
||||
totalDelta! > 0 && "text-success",
|
||||
totalDelta! < 0 && "text-error",
|
||||
)}
|
||||
>
|
||||
{totalDelta >= 0 ? "+" : ""}
|
||||
{totalDelta}
|
||||
</span>
|
||||
),
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-8 flex justify-end">
|
||||
<button
|
||||
onClick={() => {
|
||||
appendGame({});
|
||||
}}
|
||||
type="button"
|
||||
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"
|
||||
>
|
||||
<IoAdd className="mr-2 inline-block h-5 w-5" />
|
||||
{t("addGameButton")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import { last } from "lodash";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { getNewRating } from "@/utils/eloCalculator";
|
||||
import { TournamentResultsData } from "@/utils/trpc";
|
||||
|
||||
type TournamentResultsProps = {
|
||||
results: TournamentResultsData;
|
||||
playerId: string;
|
||||
kFactor: number;
|
||||
};
|
||||
|
||||
export const TournamentResults = ({
|
||||
results,
|
||||
playerId,
|
||||
kFactor,
|
||||
}: TournamentResultsProps) => {
|
||||
const t = useTranslations("Elo");
|
||||
|
||||
const playerResults = results?.find((p) => p.id === playerId);
|
||||
if (!playerResults) {
|
||||
return null;
|
||||
}
|
||||
|
||||
type Deltas = {
|
||||
rating: number;
|
||||
deltas: {
|
||||
rating: number;
|
||||
delta: number | undefined;
|
||||
opponentName: string | null;
|
||||
opponentElo: number | null;
|
||||
result: number | null;
|
||||
lostByForfeit: boolean;
|
||||
wonByForfeit: boolean;
|
||||
estimated: boolean;
|
||||
national: boolean;
|
||||
colour: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
const currentElo = playerResults.elo;
|
||||
|
||||
const calculations = !Number.isNaN(currentElo)
|
||||
? (playerResults.results ?? []).reduce<Deltas>(
|
||||
(acc, game) => {
|
||||
const info = {
|
||||
opponentName: game.opponent,
|
||||
opponentElo: game.elo,
|
||||
lostByForfeit: game.lostByForfeit,
|
||||
wonByForfeit: game.wonByForfeit,
|
||||
estimated: game.estimated,
|
||||
national: game.national,
|
||||
colour: game.colour,
|
||||
result: game.result,
|
||||
};
|
||||
|
||||
if (
|
||||
!game.wonByForfeit &&
|
||||
!game.lostByForfeit &&
|
||||
!game.estimated &&
|
||||
!game.national &&
|
||||
game.result !== null
|
||||
) {
|
||||
const { delta } = getNewRating(
|
||||
currentElo!,
|
||||
game.elo!,
|
||||
game.result as 1 | 0 | 0.5,
|
||||
kFactor,
|
||||
);
|
||||
return {
|
||||
rating: acc.rating + delta,
|
||||
deltas: [
|
||||
...acc.deltas,
|
||||
{ rating: acc.rating + delta, delta, ...info },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
rating: acc.rating,
|
||||
deltas: [
|
||||
...acc.deltas,
|
||||
{ rating: acc.rating, delta: undefined, ...info },
|
||||
],
|
||||
};
|
||||
},
|
||||
{ rating: currentElo!, deltas: [] },
|
||||
)
|
||||
: { rating: currentElo!, deltas: [] };
|
||||
|
||||
const deltas = calculations.deltas;
|
||||
const totalDelta = Math.round(
|
||||
deltas.reduce((acc, delta) => acc + (delta.delta ?? 0), 0),
|
||||
);
|
||||
|
||||
const noChangeCount = (deltas ?? []).filter(
|
||||
({ wonByForfeit, lostByForfeit, estimated, national }) =>
|
||||
wonByForfeit || lostByForfeit || estimated || national,
|
||||
).length;
|
||||
|
||||
if (playerResults.estimated || playerResults.national)
|
||||
return <div className="my-8 text-center text-error">{t("needRating")}</div>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="my-8 text-gray-900 dark:text-neutral-400">
|
||||
{t("initialRating", { rating: Math.round(playerResults.elo) })}
|
||||
</div>
|
||||
|
||||
<table className="mt-8 w-full">
|
||||
<tbody>
|
||||
{deltas.map((delta, i) => {
|
||||
const { estimated, national, lostByForfeit, wonByForfeit } = delta;
|
||||
const opponentElo = delta.opponentElo
|
||||
? ` (${delta.opponentElo} ${
|
||||
estimated ? "E" : national ? "N" : "F"
|
||||
})`
|
||||
: "";
|
||||
|
||||
const opponentName = delta.opponentName ? (
|
||||
<span>
|
||||
<span className="whitespace-nowrap font-bold">
|
||||
{delta.opponentName}
|
||||
</span>
|
||||
{opponentElo}
|
||||
</span>
|
||||
) : (
|
||||
"-"
|
||||
);
|
||||
|
||||
const playedWhite = delta.colour === "white";
|
||||
|
||||
const whitePlayer = playedWhite ? playerResults.name : opponentName;
|
||||
const blackPlayer = !playedWhite
|
||||
? playerResults.name
|
||||
: opponentName;
|
||||
const noChange =
|
||||
wonByForfeit || lostByForfeit || estimated || national;
|
||||
|
||||
const forfeit = delta.opponentName === null;
|
||||
|
||||
let result = "";
|
||||
if (wonByForfeit) {
|
||||
result = t("wonByForfeit");
|
||||
} else if (lostByForfeit) {
|
||||
result = t("lostByForfeit");
|
||||
} else if (delta.result === 0.5) {
|
||||
result = t("draw");
|
||||
} else if (
|
||||
(playedWhite && delta.result === 1) ||
|
||||
(!playedWhite && delta.result === 0)
|
||||
) {
|
||||
result = t("whiteWin");
|
||||
} else result = t("blackWin");
|
||||
|
||||
return (
|
||||
<tr key={i} className="text-gray-900 dark:text-neutral-400">
|
||||
{forfeit ? (
|
||||
<td className="pb-2">{t("forfeit")}</td>
|
||||
) : (
|
||||
<td className="pb-2">
|
||||
{whitePlayer}
|
||||
{t("vs")}
|
||||
{blackPlayer}
|
||||
</td>
|
||||
)}
|
||||
<td className="whitespace-nowrap px-2 pb-2 text-center">
|
||||
{!forfeit && result}
|
||||
</td>
|
||||
<td className="pb-2 text-right">
|
||||
{noChange ? (
|
||||
"-"
|
||||
) : (
|
||||
<span
|
||||
className={twMerge(
|
||||
deltas[i].delta! > 0 && "text-success",
|
||||
deltas[i].delta! < 0 && "text-error",
|
||||
)}
|
||||
>
|
||||
{deltas[i]!.delta! >= 0 ? "+" : ""}
|
||||
{deltas[i].delta!}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{noChangeCount > 0 && (
|
||||
<div className="mt-4 rounded border border-gray-500 p-4 text-center text-gray-500 dark:border-neutral-400 dark:text-neutral-400">
|
||||
{t("noChangeInfo", { noChangeCount })}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{deltas.length > 0 && (
|
||||
<div className="mt-8 text-right text-lg font-bold text-gray-900 dark:text-neutral-400">
|
||||
{t.rich("finalRating", {
|
||||
rating: Math.round(last(deltas)!.rating),
|
||||
delta: () => (
|
||||
<span
|
||||
className={twMerge(
|
||||
totalDelta! > 0 && "text-success",
|
||||
totalDelta! < 0 && "text-error",
|
||||
)}
|
||||
>
|
||||
{totalDelta >= 0 ? "+" : ""}
|
||||
{totalDelta}
|
||||
</span>
|
||||
),
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,279 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { isEmpty, sortBy } from "lodash";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Spinner } from "@/components/Spinner";
|
||||
import { SelectField } from "@/components/form/SelectField";
|
||||
import { TextField } from "@/components/form/TextField";
|
||||
import { fetchTournamentResultsSchema } from "@/schemas";
|
||||
import { Link } from "@/utils/navigation";
|
||||
import { trpc } from "@/utils/trpc";
|
||||
|
||||
import { KFactor } from "./KFactor";
|
||||
import { ManualEloForm } from "./ManualEloForm";
|
||||
import { TournamentResults } from "./TournamentResults";
|
||||
|
||||
const kFactors = ["40", "20", "10"];
|
||||
|
||||
const formSchema = fetchTournamentResultsSchema.extend({
|
||||
player: z.string().optional(),
|
||||
kFactor: z.string(),
|
||||
});
|
||||
|
||||
type FetchResultsFormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export default function Elo() {
|
||||
const t = useTranslations("Elo");
|
||||
type TranslationKey = Parameters<typeof t>[0];
|
||||
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const current = useMemo(
|
||||
() => new URLSearchParams(Array.from(searchParams.entries())),
|
||||
[searchParams],
|
||||
);
|
||||
|
||||
const url = searchParams.get("url") ?? "";
|
||||
const kFactorParam = searchParams.get("k");
|
||||
const player = searchParams.get("player") ?? "";
|
||||
|
||||
const kFactor =
|
||||
kFactorParam && kFactors.includes(kFactorParam) ? kFactorParam : "20";
|
||||
|
||||
const hasUrl = !isEmpty(url.trim());
|
||||
|
||||
const {
|
||||
data: allResults,
|
||||
isFetching,
|
||||
error,
|
||||
} = trpc.fetchTournamentResults.useQuery(
|
||||
{
|
||||
url: url?.trim(),
|
||||
},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: Infinity,
|
||||
cacheTime: 10 * 60 * 1000,
|
||||
enabled: hasUrl,
|
||||
retry: false,
|
||||
},
|
||||
);
|
||||
|
||||
const playerOptions = sortBy(
|
||||
(allResults ?? []).map((player) => ({
|
||||
value: player.id,
|
||||
label: player.name,
|
||||
})),
|
||||
"label",
|
||||
);
|
||||
|
||||
const form = useForm<FetchResultsFormValues>({
|
||||
resolver: zodResolver(fetchTournamentResultsSchema),
|
||||
defaultValues: {
|
||||
url: url ?? "",
|
||||
kFactor: kFactor ?? "20",
|
||||
player: player ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (input: FetchResultsFormValues) => {
|
||||
current.set("url", input.url);
|
||||
if (input.kFactor) current.set("k", input.kFactor);
|
||||
|
||||
const search = current.toString();
|
||||
const query = search ? `?${search}` : "";
|
||||
|
||||
// Push the new URL
|
||||
router.push(`${pathname}${query}`);
|
||||
};
|
||||
|
||||
const clearForm = () => {
|
||||
current.delete("url");
|
||||
current.delete("k");
|
||||
current.delete("player");
|
||||
|
||||
form.setValue("url", "");
|
||||
form.setValue("kFactor", "20");
|
||||
form.setValue("player", "");
|
||||
|
||||
const search = current.toString();
|
||||
const query = search ? `?${search}` : "";
|
||||
|
||||
router.push(`${pathname}${query}`);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// We subscribe to form changes and update the URL parameters
|
||||
const subscription = form.watch((value, { name, type }) => {
|
||||
let update = false;
|
||||
if (type === "change") {
|
||||
if (name === "player" && value.player !== player && value.player) {
|
||||
current.set("player", value.player);
|
||||
update = true;
|
||||
} else if (
|
||||
name === "kFactor" &&
|
||||
value.kFactor !== kFactor &&
|
||||
value.kFactor
|
||||
) {
|
||||
current.set("k", value.kFactor);
|
||||
update = true;
|
||||
}
|
||||
|
||||
if (update) {
|
||||
const search = current.toString();
|
||||
const query = search ? `?${search}` : "";
|
||||
router.replace(`${pathname}${query}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
return () => subscription.unsubscribe();
|
||||
}, [current, form, form.watch, kFactor, pathname, player, router]);
|
||||
|
||||
useEffect(() => {
|
||||
// When the URL changes, we update the form values
|
||||
if (url !== form.getValues("url")) {
|
||||
form.setValue("url", url);
|
||||
}
|
||||
|
||||
if (player !== form.getValues("player")) {
|
||||
form.setValue("player", player);
|
||||
}
|
||||
|
||||
if (kFactor !== form.getValues("kFactor")) {
|
||||
form.setValue("kFactor", form.getValues("kFactor"));
|
||||
}
|
||||
}, [searchParams, form, url, player, kFactor]);
|
||||
|
||||
if (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
const playerResults = allResults?.find((p) => p.id === player);
|
||||
|
||||
return (
|
||||
<section className="grid place-items-center bg-white pb-20 dark:bg-gray-800">
|
||||
<div className="max-w-xl px-4 py-8 lg:py-16">
|
||||
<h2
|
||||
className="mb-10 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">
|
||||
{t("info")}
|
||||
</p>
|
||||
|
||||
{hasUrl && !isFetching && !error && (
|
||||
<div className="mx-auto mb-8 flex justify-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={clearForm}
|
||||
className="rounded-lg border border-primary px-3 py-2 text-center text-sm text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
|
||||
>
|
||||
{t("enterManualResultsButton")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormProvider {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
||||
<div className="flex items-end gap-4">
|
||||
<TextField
|
||||
name="url"
|
||||
control={form.control}
|
||||
label={t("resultsUrlLabel")}
|
||||
placeholder={t("resultsUrlLabel")}
|
||||
/>
|
||||
<button
|
||||
disabled={form.formState.isSubmitting}
|
||||
type="submit"
|
||||
className="rounded-lg border border-transparent 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("fetchResultsButton")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isFetching && (
|
||||
<div className="mt-8 flex justify-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="mt-8 text-center text-error">
|
||||
{error.message.startsWith("ERR_")
|
||||
? t(error.message as TranslationKey)
|
||||
: t.rich("unknownError", {
|
||||
contact: (chunks) => (
|
||||
<Link className="underline" href="/contact-us">
|
||||
{chunks}
|
||||
</Link>
|
||||
),
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isFetching && playerOptions.length > 0 && (
|
||||
<div>
|
||||
<div className="grid w-full grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<SelectField
|
||||
name="player"
|
||||
control={form.control}
|
||||
required
|
||||
label={t("choosePlayerLabel")}
|
||||
placeholder={t("choosePlayerPlaceholder")}
|
||||
options={playerOptions}
|
||||
isClearable={false}
|
||||
/>
|
||||
|
||||
<SelectField
|
||||
name="kFactor"
|
||||
control={form.control}
|
||||
label={t("kFactorLabel")}
|
||||
options={["40", "20", "10"].map((k) => ({
|
||||
value: k,
|
||||
label: k,
|
||||
}))}
|
||||
isClearable={false}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<KFactor className="mt-2" />
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</FormProvider>
|
||||
|
||||
{hasUrl && !isFetching && player && playerResults && !error && (
|
||||
<TournamentResults
|
||||
playerId={player}
|
||||
kFactor={parseInt(kFactor)}
|
||||
results={allResults ?? []}
|
||||
/>
|
||||
)}
|
||||
|
||||
{((!hasUrl && !isFetching) || !!error) && (
|
||||
<>
|
||||
<div className="relative my-8">
|
||||
<div className="absolute top-1/2 z-10 h-[1px] w-full bg-gray-500 dark:bg-gray-400" />
|
||||
<div className="relative z-20 mx-auto w-fit bg-white px-2 py-1 text-gray-500 dark:bg-gray-800 dark:text-gray-400">
|
||||
{t("useManualLabel")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ManualEloForm />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { ReactNode } from "react";
|
||||
|
||||
import { NextIntlClientProvider } from "next-intl";
|
||||
import { getTranslator } from "next-intl/server";
|
||||
import { Inter, Julius_Sans_One } from "next/font/google";
|
||||
import { notFound } from "next/navigation";
|
||||
import Script from "next/script";
|
||||
|
||||
import "@/css/globals.css";
|
||||
import Providers from "@/providers";
|
||||
|
||||
import Footer from "./components/Footer";
|
||||
import Navbar from "./components/Navbar";
|
||||
|
||||
const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
|
||||
const title = Julius_Sans_One({
|
||||
subsets: ["latin"],
|
||||
weight: "400",
|
||||
variable: "--font-title",
|
||||
});
|
||||
|
||||
export async function generateMetadata({
|
||||
params: { locale },
|
||||
}: {
|
||||
params: { locale?: string };
|
||||
}) {
|
||||
// While the `locale` is required, the namespace is optional and
|
||||
// identical to the parameter that `useTranslations` accepts.
|
||||
const t = await getTranslator(locale ?? "fr", "Metadata");
|
||||
|
||||
return {
|
||||
title: t("title"),
|
||||
description: t("description"),
|
||||
keywords: t("keywords"),
|
||||
};
|
||||
}
|
||||
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
params: { locale },
|
||||
}: {
|
||||
children: ReactNode;
|
||||
params: { locale?: string };
|
||||
}) {
|
||||
let messages;
|
||||
try {
|
||||
messages = (await import(`@/messages/${locale}.json`)).default;
|
||||
} catch (error) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<html lang={locale} className={`${inter.variable} ${title.variable}`}>
|
||||
<head>
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no, user-scalable=no, viewport-fit=cover"
|
||||
/>
|
||||
|
||||
<meta name="application-name" content="Echecs France" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="Echecs France" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="theme-color" content="#00A1F0" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
</head>
|
||||
<body>
|
||||
<Providers>
|
||||
<NextIntlClientProvider locale={locale} messages={messages}>
|
||||
<div className="bg-white font-sans leading-normal tracking-normal dark:bg-gray-800">
|
||||
<Navbar />
|
||||
<div className="relative min-h-content">{children}</div>
|
||||
<Footer />
|
||||
</div>
|
||||
</NextIntlClientProvider>
|
||||
<Script
|
||||
defer
|
||||
src="https://app.tinyanalytics.io/pixel/HyoumUokLr9exPgX"
|
||||
></Script>
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useTranslations } from "next-intl";
|
||||
import Image from "next/image";
|
||||
|
||||
import bgImage from "@/img/map-bg.jpg";
|
||||
import { Link } from "@/utils/navigation";
|
||||
|
||||
export default function Home() {
|
||||
const t = useTranslations("Home");
|
||||
|
||||
return (
|
||||
<header className="relative mb-12 flex min-h-content items-center justify-center">
|
||||
<div className="absolute h-full w-full py-4 brightness-[0.2]">
|
||||
<Image
|
||||
src={bgImage}
|
||||
alt="Background image of France"
|
||||
fill={true}
|
||||
style={{ objectFit: "cover" }}
|
||||
/>
|
||||
</div>
|
||||
<div className="z-10 py-4 text-center text-white">
|
||||
<h1 className="p-5 font-title text-5xl" data-test="header1">
|
||||
{t("title")}
|
||||
</h1>
|
||||
<h2 className="p-5 text-3xl">{t("purpose")}</h2>
|
||||
<h3 className="mb-5 p-5 text-xl">
|
||||
{t.rich("how", {
|
||||
link: (chunks) => (
|
||||
<a href="http://www.echecs.asso.fr/" target="_blank">
|
||||
<abbr title="Fédération Française des Échecs">{chunks}</abbr>
|
||||
</a>
|
||||
),
|
||||
})}
|
||||
</h3>
|
||||
<Link
|
||||
href="/tournaments"
|
||||
className="mb-2 rounded-lg bg-primary px-5 py-2.5 text-center text-sm font-medium text-white hover:bg-primary-700 hover:bg-gradient-to-br focus:outline-none focus:ring-4 focus:ring-primary-300 dark:focus:ring-primary-800"
|
||||
>
|
||||
{t("mapLink")}
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import L from "leaflet";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useMap } from "react-leaflet";
|
||||
|
||||
import { filteredTournamentsByTimeControlAtom } from "@/atoms";
|
||||
import { TimeControlColours } from "@/constants";
|
||||
import { TimeControl } from "@/types";
|
||||
|
||||
const Legend = () => {
|
||||
const at = useTranslations("App");
|
||||
const map = useMap();
|
||||
const tournaments = useAtomValue(filteredTournamentsByTimeControlAtom);
|
||||
|
||||
const timeControls = useMemo(
|
||||
() =>
|
||||
[
|
||||
TimeControl.Classic,
|
||||
TimeControl.Rapid,
|
||||
TimeControl.Blitz,
|
||||
TimeControl.Other,
|
||||
].filter((tc) => tournaments.some((t) => t.timeControl === tc)),
|
||||
[tournaments],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (map) {
|
||||
// @ts-ignore
|
||||
const legend = L.control({ position: "bottomleft" });
|
||||
|
||||
legend.onAdd = () => {
|
||||
const div = L.DomUtil.create("div", "map-legend");
|
||||
div.setAttribute(
|
||||
"style",
|
||||
"background: white; color: black; border: 2px solid grey; border-radius: 6px; padding: 10px;",
|
||||
);
|
||||
|
||||
div.innerHTML = `
|
||||
<ul>
|
||||
${timeControls
|
||||
.map(
|
||||
(tc) => `
|
||||
<li>
|
||||
<span class="block h-4 w-7 border border-[#999] float-left mr-1" style="background: ${
|
||||
TimeControlColours[tc]
|
||||
}"></span>${at("timeControlEnum", { tc })}
|
||||
</li>
|
||||
`,
|
||||
)
|
||||
.join("")}
|
||||
</ul>`;
|
||||
return div;
|
||||
};
|
||||
|
||||
legend.addTo(map);
|
||||
}
|
||||
}, [map, at]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return null;
|
||||
};
|
||||
|
||||
export default Legend;
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import {
|
||||
blitzAtom,
|
||||
classicAtom,
|
||||
otherAtom,
|
||||
rapidAtom,
|
||||
tournamentsAtom,
|
||||
} from "@/atoms";
|
||||
import { TimeControl } from "@/types";
|
||||
|
||||
const TimeControlFilters = () => {
|
||||
const at = useTranslations("App");
|
||||
const tournaments = useAtomValue(tournamentsAtom);
|
||||
|
||||
const classic = useAtom(classicAtom);
|
||||
const rapid = useAtom(rapidAtom);
|
||||
const blitz = useAtom(blitzAtom);
|
||||
const other = useAtom(otherAtom);
|
||||
|
||||
const checkboxes = [
|
||||
{ tc: TimeControl.Classic, atom: classic },
|
||||
{ tc: TimeControl.Rapid, atom: rapid },
|
||||
{ tc: TimeControl.Blitz, atom: blitz },
|
||||
{ tc: TimeControl.Other, atom: other },
|
||||
].filter(({ tc }) => tournaments.some((t) => t.timeControl === tc));
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{checkboxes.map(({ tc, atom }, i) => (
|
||||
<div key={i} className="text-gray-900 dark:text-white">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mr-2 h-4 w-4 rounded border-gray-400 text-primary focus:ring-primary"
|
||||
checked={atom[0]}
|
||||
onChange={() => atom[1](!atom[0])}
|
||||
/>
|
||||
{at("timeControlEnum", { tc })}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TimeControlFilters;
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import L, { LatLngLiteral } from "leaflet";
|
||||
import "leaflet-defaulticon-compatibility";
|
||||
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
|
||||
import "leaflet.smooth_marker_bouncing";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import { countBy, groupBy } from "lodash";
|
||||
|
||||
import { filteredTournamentsByTimeControlAtom, normsOnlyAtom } from "@/atoms";
|
||||
import { Map, MapMarker } from "@/components/Map";
|
||||
import { TimeControlColours } from "@/constants";
|
||||
import { generatePieSVG } from "@/lib/pie";
|
||||
import { TimeControl } from "@/types";
|
||||
|
||||
import Legend from "./Legend";
|
||||
import TimeControlFilters from "./TimeControlFilters";
|
||||
import { TournamentMarker } from "./TournamentMarker";
|
||||
|
||||
const TournamentMap = () => {
|
||||
const tournaments = useAtomValue(filteredTournamentsByTimeControlAtom);
|
||||
const normsOnly = useAtomValue(normsOnlyAtom);
|
||||
|
||||
const filteredTournaments = useMemo(
|
||||
() => tournaments.filter((t) => (normsOnly ? t.norm : true)),
|
||||
[normsOnly, tournaments],
|
||||
);
|
||||
|
||||
const groupedTournaments = groupBy(filteredTournaments, (t) => t.groupId);
|
||||
|
||||
const createClusterCustomIcon = useCallback((cluster: any) => {
|
||||
const childCount = cluster.getChildCount();
|
||||
const children = cluster.getAllChildMarkers();
|
||||
|
||||
// We added the time control as the class name when creating the marker
|
||||
const timeControlCounts = countBy(
|
||||
children,
|
||||
(child: any) => child.options.icon.options.className,
|
||||
);
|
||||
|
||||
const html = `
|
||||
<div>
|
||||
${generatePieSVG(
|
||||
"absolute w-[30px]",
|
||||
15,
|
||||
[
|
||||
TimeControl.Classic,
|
||||
TimeControl.Rapid,
|
||||
TimeControl.Blitz,
|
||||
TimeControl.Other,
|
||||
].map((tc) => ({
|
||||
value: timeControlCounts[tc] ?? 0,
|
||||
colour: TimeControlColours[tc],
|
||||
})),
|
||||
)}
|
||||
<span class="text-white font-semibold relative z-[300]">${childCount}</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return new L.DivIcon({
|
||||
html,
|
||||
className: "marker-cluster bg-gray-600/20",
|
||||
iconSize: new L.Point(40, 40),
|
||||
});
|
||||
}, []);
|
||||
|
||||
const markers: MapMarker[] = useMemo(
|
||||
() =>
|
||||
Object.values(groupedTournaments).map((tournamentGroup) => {
|
||||
const { groupId } = tournamentGroup[0];
|
||||
return {
|
||||
markerId: groupId,
|
||||
tableIds: tournamentGroup.map((t) => t.id),
|
||||
component: (
|
||||
<TournamentMarker key={groupId} tournamentGroup={tournamentGroup} />
|
||||
),
|
||||
};
|
||||
}),
|
||||
[groupedTournaments],
|
||||
);
|
||||
|
||||
return (
|
||||
<Map
|
||||
markers={markers}
|
||||
legend={<Legend />}
|
||||
filters={<TimeControlFilters />}
|
||||
iconCreateFunction={createClusterCustomIcon}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default TournamentMap;
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { forwardRef, useImperativeHandle, useMemo, useRef } from "react";
|
||||
|
||||
import { useSetAtom } from "jotai";
|
||||
import L from "leaflet";
|
||||
import { last } from "lodash";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { FaTrophy } from "react-icons/fa";
|
||||
import { Marker, MarkerProps, Popup } from "react-leaflet";
|
||||
|
||||
import { debouncedHoveredMapIdAtom } from "@/atoms";
|
||||
import type { MarkerRef } from "@/components/Map";
|
||||
import { TimeControlColours } from "@/constants";
|
||||
import type { BouncingMarker } from "@/leafletTypes";
|
||||
import { Tournament } from "@/types";
|
||||
|
||||
type TournamentMarkerProps = {
|
||||
tournamentGroup: Tournament[];
|
||||
} & Omit<MarkerProps, "position">;
|
||||
|
||||
export const TournamentMarker = forwardRef<MarkerRef, TournamentMarkerProps>(
|
||||
({ tournamentGroup, ...markerProps }, ref) => {
|
||||
const t = useTranslations("Tournaments");
|
||||
const markerRef = useRef<L.Marker<any> | null>(null);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
getMarker: () => markerRef.current!,
|
||||
bounce: () => {
|
||||
const bouncingMarker = markerRef.current as BouncingMarker;
|
||||
bouncingMarker.setBouncingOptions({ contractHeight: 0 });
|
||||
bouncingMarker.bounce();
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const { date, latLng, groupId, timeControl } = tournamentGroup[0];
|
||||
|
||||
const setHoveredMapId = useSetAtom(debouncedHoveredMapIdAtom);
|
||||
|
||||
const iconOptions = useMemo(
|
||||
() =>
|
||||
new L.DivIcon({
|
||||
html: `
|
||||
<svg x="0px" y="0px" viewBox="0 0 365 560" enable-background="new 0 0 365 560" xml:space="preserve">
|
||||
<g><circle fill="#FFFFFF" cx="182" cy="180" r="70" /></g>
|
||||
<g><path stroke="#666666" stroke-width="10" fill="${TimeControlColours[timeControl]}" d="M182.9,551.7c0,0.1,0.2,0.3,0.2,0.3S358.3,283,358.3,194.6c0-130.1-88.8-186.7-175.4-186.9 C96.3,7.9,7.5,64.5,7.5,194.6c0,88.4,175.3,357.4,175.3,357.4S182.9,551.7,182.9,551.7z M122.2,187.2c0-33.6,27.2-60.8,60.8-60.8 c33.6,0,60.8,27.2,60.8,60.8S216.5,248,182.9,248C149.4,248,122.2,220.8,122.2,187.2z"/></g>
|
||||
</svg>
|
||||
`,
|
||||
className: timeControl,
|
||||
iconSize: [24, 40],
|
||||
iconAnchor: [12, 40],
|
||||
popupAnchor: [1, -40],
|
||||
}),
|
||||
[timeControl],
|
||||
);
|
||||
|
||||
const startDate = date;
|
||||
const endDate = last(tournamentGroup)!.date;
|
||||
|
||||
return (
|
||||
<Marker
|
||||
ref={markerRef}
|
||||
position={latLng}
|
||||
icon={iconOptions}
|
||||
eventHandlers={{
|
||||
mouseover: () => setHoveredMapId(groupId),
|
||||
mouseout: () => setHoveredMapId(null),
|
||||
}}
|
||||
{...markerProps}
|
||||
>
|
||||
<Popup maxWidth={10000}>
|
||||
<div className="flex max-w-[calc(100vw-80px)] flex-col gap-3 lg:max-w-[calc(100vw/2-80px)]">
|
||||
<b>
|
||||
{date}
|
||||
{endDate !== startDate && ` - ${endDate}`}
|
||||
</b>
|
||||
|
||||
<div className="flex flex-col gap-0">
|
||||
{tournamentGroup.map((tournament) => (
|
||||
<a
|
||||
key={tournament.id}
|
||||
href={tournament.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{tournament.tournament}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tournamentGroup.some((t) => t.norm) && (
|
||||
<div className="flex items-center">
|
||||
<FaTrophy className="mr-3 h-4 w-4" />
|
||||
{t("norm")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{t("approx")}
|
||||
</div>
|
||||
</Popup>
|
||||
</Marker>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
TournamentMarker.displayName = "TournamentMarker";
|
||||
@@ -0,0 +1,176 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useAtom, useAtomValue, useSetAtom } from "jotai";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { FaExternalLinkAlt } from "react-icons/fa";
|
||||
import { FaTrophy } from "react-icons/fa";
|
||||
import { Tooltip } from "react-tooltip";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import {
|
||||
debouncedHoveredListIdAtom,
|
||||
debouncedHoveredMapIdAtom,
|
||||
filteredTournamentsListAtom,
|
||||
hoveredMapIdAtom,
|
||||
normsOnlyAtom,
|
||||
syncVisibleAtom,
|
||||
} from "@/atoms";
|
||||
import ScrollToTopButton from "@/components/ScrollToTopButton";
|
||||
import SearchBar from "@/components/SearchBar";
|
||||
import { useBreakpoint } from "@/hooks/tailwind";
|
||||
|
||||
import TimeControlFilters from "./TimeControlFilters";
|
||||
|
||||
const TournamentTable = () => {
|
||||
const t = useTranslations("Tournaments");
|
||||
const at = useTranslations("App");
|
||||
|
||||
const filteredTournaments = useAtomValue(filteredTournamentsListAtom);
|
||||
const [syncVisible, setSyncVisible] = useAtom(syncVisibleAtom);
|
||||
const [normsOnly, setNormsOnly] = useAtom(normsOnlyAtom);
|
||||
const hoveredMapId = useAtomValue(hoveredMapIdAtom);
|
||||
const debouncedHoveredMapId = useAtomValue(debouncedHoveredMapIdAtom);
|
||||
const setHoveredListId = useSetAtom(debouncedHoveredListIdAtom);
|
||||
|
||||
const isLg = useBreakpoint("lg");
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLg || debouncedHoveredMapId === null) return;
|
||||
const tournamentRow = document.querySelector(
|
||||
`[data-group-id="${debouncedHoveredMapId}"]`,
|
||||
);
|
||||
|
||||
tournamentRow?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [debouncedHoveredMapId, isLg]);
|
||||
|
||||
return (
|
||||
<section
|
||||
className="grid w-full auto-rows-max pb-20 lg:col-start-2 lg:col-end-3 lg:h-content lg:overflow-y-scroll lg:pb-0"
|
||||
id="listing"
|
||||
>
|
||||
<div className="z-10 flex w-full flex-wrap items-center justify-between gap-3 p-3">
|
||||
<SearchBar />
|
||||
|
||||
<div className="flex flex-col gap-0 text-gray-900 dark:text-white">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mr-2 h-4 w-4 rounded border-gray-400 text-primary focus:ring-primary"
|
||||
checked={syncVisible}
|
||||
onChange={() => setSyncVisible(!syncVisible)}
|
||||
/>
|
||||
{t("syncWithMapCheckbox")}
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mr-2 h-4 w-4 rounded border-gray-400 text-primary focus:ring-primary"
|
||||
checked={normsOnly}
|
||||
onChange={() => setNormsOnly(!normsOnly)}
|
||||
/>
|
||||
{t("normsOnly")}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="hidden lg:block">
|
||||
<TimeControlFilters />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ScrollToTopButton />
|
||||
|
||||
<div className="overflow-x-scroll">
|
||||
<table className="relative min-w-full table-fixed text-center text-xs lg:w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="sticky top-0 bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("date")}
|
||||
</th>
|
||||
<th className="sticky top-0 bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("town")}
|
||||
</th>
|
||||
<th className="sticky top-0 bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("tournament")}
|
||||
</th>
|
||||
<th className="sticky top-0 bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("timeControl")}
|
||||
</th>
|
||||
<th className="sticky top-0 w-[50px] bg-primary-600 p-3 text-white dark:bg-gray-600">
|
||||
{t("ffe")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{filteredTournaments.length === 0 ? (
|
||||
<tr className="bg-white text-gray-900 dark:bg-gray-800 dark:text-white">
|
||||
<td colSpan={4} className="p-3">
|
||||
{t("noneFound")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredTournaments.map((tournament) => (
|
||||
<tr
|
||||
key={tournament.id}
|
||||
id={tournament.id}
|
||||
data-group-id={tournament.groupId}
|
||||
onMouseEnter={() => setHoveredListId(tournament.id)}
|
||||
onMouseLeave={() => setHoveredListId(null)}
|
||||
className={twMerge(
|
||||
"scroll-m-20 bg-white text-gray-900 hover:bg-gray-200 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-900",
|
||||
hoveredMapId === tournament.groupId &&
|
||||
"bg-gray-200 dark:bg-gray-900",
|
||||
)}
|
||||
>
|
||||
<td className="px-1 py-2 sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
{tournament.date}
|
||||
</td>
|
||||
<td className="px-1 py-2 sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
{tournament.town}
|
||||
</td>
|
||||
<td className="px-1 py-2 text-left sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
<span>
|
||||
{tournament.norm && (
|
||||
<FaTrophy
|
||||
className="mr-2 inline-block h-4 w-4"
|
||||
data-norm="norm"
|
||||
/>
|
||||
)}
|
||||
{tournament.tournament}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-1 py-2 sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
{at("timeControlEnum", { tc: tournament.timeControl })}
|
||||
</td>
|
||||
<td className="px-1 py-2 sm:px-3 sm:py-3 lg:px-3 lg:py-3">
|
||||
<div className="flex justify-center">
|
||||
<a
|
||||
href={tournament.url}
|
||||
target="_blank"
|
||||
className="text-primary hover:text-primary-800"
|
||||
>
|
||||
<FaExternalLinkAlt />
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<Tooltip anchorSelect="[data-norm='norm']">
|
||||
<div className="flex items-center">
|
||||
<FaTrophy className="mr-3 h-4 w-4" />
|
||||
{t("norm")}
|
||||
</div>
|
||||
</Tooltip>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default TournamentTable;
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { useHydrateAtoms } from "jotai/utils";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
import { tournamentsAtom } from "@/atoms";
|
||||
import LoadingMap from "@/components/LoadingMap";
|
||||
import { Tournament } from "@/types";
|
||||
|
||||
import TournamentTable from "./TournamentTable";
|
||||
|
||||
type TournamentsDisplayProps = {
|
||||
tournaments: Tournament[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Imports the tournament map component, ensuring CSR only.
|
||||
* @remarks SSR is not supported by react-leaflet
|
||||
*/
|
||||
const TournamentMap = dynamic(() => import("./TournamentMap"), {
|
||||
ssr: false,
|
||||
loading: LoadingMap,
|
||||
});
|
||||
|
||||
export default function TournamentsDisplay({
|
||||
tournaments,
|
||||
}: TournamentsDisplayProps) {
|
||||
useHydrateAtoms([[tournamentsAtom, tournaments]]);
|
||||
|
||||
return (
|
||||
<main className="relative grid h-full w-full lg:grid-cols-2">
|
||||
<div>
|
||||
<TournamentMap />
|
||||
</div>
|
||||
<div className="relative bg-white dark:bg-gray-800 lg:overflow-y-auto">
|
||||
<TournamentTable />
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { differenceInDays, isSameDay, parse } from "date-fns";
|
||||
import { groupBy } from "lodash";
|
||||
|
||||
import clientPromise from "@/lib/mongodb";
|
||||
import { TournamentData } from "@/types";
|
||||
import { TimeControl, Tournament } from "@/types";
|
||||
import { errorLog } from "@/utils/logger";
|
||||
|
||||
import TournamentsDisplay from "./TournamentsDisplay";
|
||||
|
||||
export const revalidate = 3600; // Revalidate cache every 6 hours
|
||||
|
||||
const tcMap: Record<TournamentData["time_control"], TimeControl> = {
|
||||
"Cadence Lente": TimeControl.Classic,
|
||||
Rapide: TimeControl.Rapid,
|
||||
Blitz: TimeControl.Blitz,
|
||||
};
|
||||
|
||||
const getTournaments = async () => {
|
||||
try {
|
||||
const client = await clientPromise;
|
||||
const db = client.db("tournamentsFranceDB");
|
||||
const data = await db
|
||||
.collection("tournaments")
|
||||
.aggregate<TournamentData>([
|
||||
{
|
||||
$addFields: {
|
||||
dateParts: {
|
||||
$dateFromString: {
|
||||
dateString: "$date",
|
||||
format: "%d/%m/%Y",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$sort: {
|
||||
dateParts: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
$unset: "dateParts",
|
||||
},
|
||||
])
|
||||
.toArray();
|
||||
|
||||
// Group the tournaments by their location
|
||||
const groupedByLocation = groupBy(
|
||||
data,
|
||||
(t) => `${t.coordinates[0]}_${t.coordinates[1]}`,
|
||||
);
|
||||
|
||||
// For each location, create an array of arrays of contiguous dates for this location
|
||||
const dateRangesByLocation: Record<string, Date[][]> = {};
|
||||
for (const location in groupedByLocation) {
|
||||
const tournaments = groupedByLocation[location];
|
||||
|
||||
// Note that this works since the tournaments are sorted by date
|
||||
const dateRanges = tournaments.reduce<Date[][]>(
|
||||
(acc, tournament) => {
|
||||
const group = acc[acc.length - 1];
|
||||
const date = parse(tournament.date, "dd/MM/yyyy", new Date());
|
||||
const diff = differenceInDays(date, group[group.length - 1] ?? date);
|
||||
if (diff > 1) {
|
||||
acc.push([date]);
|
||||
} else if (group.length === 0 || diff === 1) {
|
||||
group.push(date);
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
[[]],
|
||||
);
|
||||
|
||||
dateRangesByLocation[location] = dateRanges;
|
||||
}
|
||||
|
||||
return data.map<Tournament>((t) => {
|
||||
const location = `${t.coordinates[0]}_${t.coordinates[1]}`;
|
||||
const date = parse(t.date, "dd/MM/yyyy", new Date());
|
||||
const dateRanges = dateRangesByLocation[location];
|
||||
const rangeIndex = dateRanges.findIndex((ranges) =>
|
||||
ranges.some((d) => isSameDay(d, date)),
|
||||
);
|
||||
|
||||
// We place each tournament into a group based on location and date and time control, so that
|
||||
// we can display a single map marker.
|
||||
const timeControl = tcMap[t.time_control] ?? TimeControl.Other;
|
||||
const groupId = `${location}_${rangeIndex}_${timeControl}`;
|
||||
|
||||
return {
|
||||
id: t._id.toString(),
|
||||
groupId,
|
||||
tournament: t.tournament,
|
||||
town: t.town,
|
||||
department: t.department,
|
||||
date: t.date,
|
||||
url: t.url,
|
||||
timeControl,
|
||||
latLng: { lat: t.coordinates[0], lng: t.coordinates[1] },
|
||||
norm: t.norm_tournament,
|
||||
pending: t.pending,
|
||||
status: t.status,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
errorLog(error);
|
||||
throw new Error("Error fetching tournament data");
|
||||
}
|
||||
};
|
||||
|
||||
export default async function Tournaments() {
|
||||
const tournaments = await getTournaments();
|
||||
return <TournamentsDisplay tournaments={tournaments} />;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
FetchCreateContextFnOptions,
|
||||
fetchRequestHandler,
|
||||
} from "@trpc/server/adapters/fetch";
|
||||
|
||||
import { appRouter } from "@/server/appRouter";
|
||||
|
||||
const handler = (request: Request) => {
|
||||
return fetchRequestHandler({
|
||||
endpoint: "/api/trpc",
|
||||
req: request,
|
||||
router: appRouter,
|
||||
createContext: function (
|
||||
opts: FetchCreateContextFnOptions,
|
||||
): object | Promise<object> {
|
||||
return {};
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 93 KiB |
@@ -0,0 +1,12 @@
|
||||
import { MetadataRoute } from "next";
|
||||
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return {
|
||||
rules: {
|
||||
userAgent: "*",
|
||||
allow: "/",
|
||||
disallow: "/api/",
|
||||
},
|
||||
sitemap: "https://echecsfrance/sitemap.xml",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { MetadataRoute } from "next";
|
||||
|
||||
import { locales, pathnames } from "@/utils/navigation";
|
||||
|
||||
export default function sitemap(): MetadataRoute.Sitemap {
|
||||
return locales.flatMap((locale) => {
|
||||
const prefix = `https://echecsfrance.com${
|
||||
locale === "fr" ? "" : `/${locale}`
|
||||
}`;
|
||||
|
||||
const paths = Object.keys(pathnames) as Array<keyof typeof pathnames>;
|
||||
|
||||
return paths.map((pathname) => {
|
||||
const route = pathnames[pathname];
|
||||
if (typeof route === "string") {
|
||||
return {
|
||||
url: `${prefix}${route}`,
|
||||
lastModified: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
url: `${prefix}${route[locale]}`,
|
||||
lastModified: new Date(),
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user