Update packages (and fix intl)

This commit is contained in:
Timothy Armes
2023-09-13 20:33:56 +02:00
parent cebf5d98b8
commit bff704077c
43 changed files with 1147 additions and 1597 deletions
+74
View File
@@ -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 MapEvents from "@/app/[locale]/components/MapEvents";
import { mapBoundsAtom } from "@/app/atoms";
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='&copy; <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,213 @@
"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 "@/app/[locale]/components/InfoMessage";
import InfoMessage from "@/app/[locale]/components/InfoMessage";
import LoadingMap from "@/app/[locale]/components/LoadingMap";
import { DateField } from "@/app/[locale]/components/form/DateField";
import { SelectField } from "@/app/[locale]/components/form/SelectField";
import { SwitchField } from "@/app/[locale]/components/form/SwitchField";
import { TextAreaField } from "@/app/[locale]/components/form/TextAreaField";
import { TextField } from "@/app/[locale]/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"
label={t("tournamentNameLabel")}
placeholder={t("tournamentNamePlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<DateField name="tournament.date" label={t("dateLabel")} required />
</div>
<div className="col-span-2 sm:col-span-1">
<TextField
name="tournament.url"
label={t("urlLabel")}
placeholder={t("urlPlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<SelectField
name="tournament.time_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"
label={t("normLabel")}
/>
</div>
<div className="col-span-4">
<TextField
name="tournament.address"
label={t("addressLabel")}
placeholder={t("addressPlaceholder")}
required
/>
</div>
<div className="col-span-4 sm:col-span-2">
<TextField
name="tournament.town"
label={t("townLabel")}
placeholder={t("townPlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<TextField
name="tournament.department"
label={t("departmentLabel")}
placeholder={t("departmentPlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<TextField
name="tournament.country"
label={t("countryLabel")}
placeholder={t("countryPlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<TextField
name="name"
label={t("yourNameLabel")}
placeholder={t("yourNamePlaceholder")}
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<TextField
name="email"
label={t("yourEmailLabel")}
placeholder={t("yourEmailPlaceholder")}
required
/>
</div>
<div className="col-span-4 row-span-2 sm:col-span-2">
<TextAreaField
name="message"
label={t("messageLabel")}
rows={6}
placeholder={t("messagePlaceholder")}
/>
</div>
<div className="col-span-2 sm:col-span-1">
<TextField
name="tournament.coordinates.0"
label={t("latLabel")}
type="number"
required
/>
</div>
<div className="col-span-2 sm:col-span-1">
<TextField
name="tournament.coordinates.1"
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;
+26
View File
@@ -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>
);
}
+50
View File
@@ -0,0 +1,50 @@
import { useTranslations } from "next-intl";
import Link from "next-intl/link";
import { FaGithub, FaRegEnvelope } from "react-icons/fa";
import ThemeSwitcher from "@/app/[locale]/components/ThemeSwitcher";
export default function Footer() {
const t = useTranslations("Footer");
return (
<footer
className="fixed bottom-0 z-30 flex h-20 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="text-center">
&copy; {new Date().getFullYear()} - Owen&nbsp;Rees & Timothy&nbsp;Armes
</div>
<div className="flex items-center py-2 hover:[&_a]:opacity-80">
<Link
href="https://github.com/TheRealOwenRees/echecsfrance"
target="_blank"
aria-label={t("githubAria")}
className="mr-4"
>
<FaGithub />
</Link>
<Link
href="/contactez-nous"
aria-label={t("contactAria")}
className="mr-4"
>
<FaRegEnvelope />
</Link>
<div className="mr-4 space-x-2 text-xs">
<Link href="/" locale="fr">
FR
</Link>
<span>|</span>
<Link href="/" locale="en">
EN
</Link>
</div>
<div className="text-xs hover:opacity-80">
<ThemeSwitcher />
</div>
</div>
</footer>
);
}
+50
View File
@@ -0,0 +1,50 @@
"use client";
import { useRef, useState } from "react";
import { twMerge } from "tailwind-merge";
import HamburgerMenu from "./HamburgerMenu";
const Hamburger = () => {
const [menuVisible, setMenuVisible] = useState(false);
const hamburgerButtonRef = useRef<HTMLDivElement>(null);
return (
<>
<div
ref={hamburgerButtonRef}
className="hamburger-button relative z-[99999] space-y-2"
data-test="hamburger-button"
onClick={() => setMenuVisible(!menuVisible)}
>
<div
className={twMerge(
"h-0.5 w-8 bg-gray-600 transition-all duration-300 ease-in-out dark:bg-white",
menuVisible &&
"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",
menuVisible && "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",
menuVisible && "-translate-y-2.5 -rotate-45 bg-white",
)}
></div>
</div>
<HamburgerMenu
menuVisible={menuVisible}
setMenuVisible={setMenuVisible}
hamburgerButtonRef={hamburgerButtonRef}
/>
</>
);
};
export default Hamburger;
+94
View File
@@ -0,0 +1,94 @@
import { Dispatch, RefObject, SetStateAction, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import Link from "next-intl/link";
import { twMerge } from "tailwind-merge";
import useHamburgerClose from "@/hooks/useHamburgerClose";
interface HamburgerMenuState {
menuVisible: boolean;
setMenuVisible: Dispatch<SetStateAction<boolean>>;
hamburgerButtonRef: RefObject<HTMLDivElement>;
}
const HamburgerMenu = ({
menuVisible,
setMenuVisible,
hamburgerButtonRef,
}: HamburgerMenuState) => {
const t = useTranslations("Nav");
const [mouseOverMenu, setMouseOverMenu] = useState(false);
const timeoutRef = useRef<NodeJS.Timeout | undefined>();
const menuRef = useRef<HTMLDivElement>(null);
const menuTimeout = () => {
timeoutRef.current = setTimeout(() => {
setMenuVisible(false);
setMouseOverMenu(false);
}, 4000);
};
const handleMouseEnterMenu = () => {
setMouseOverMenu(true);
clearTimeout(timeoutRef.current);
};
const handleMouseLeaveMenu = () => {
setMouseOverMenu(false);
clearTimeout(timeoutRef.current);
};
useHamburgerClose({
menuVisible,
setMenuVisible,
menuRef,
hamburgerButtonRef,
mouseOverMenu,
setMouseOverMenu,
timeoutRef,
menuTimeout,
});
return (
<div
ref={menuRef}
className={twMerge(
"fixed right-0 top-0 z-[9999] h-[calc(100svh-5rem)] w-full",
"flex items-center justify-center bg-primary-600 transition-transform duration-200 ease-linear dark:bg-gray-600 md:hidden",
!menuVisible && "translate-x-full",
)}
onMouseEnter={handleMouseEnterMenu}
onMouseLeave={handleMouseLeaveMenu}
>
<ul className="list-reset text-white">
<li className="py-5 text-center text-xl">
<Link
href="/tournois"
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
href="/qui-sommes-nous"
className="border-b-2 border-transparent transition-all duration-300 ease-in-out hover:border-white"
>
{t("about")}
</Link>
</li>
<li className="py-5 text-center text-xl">
<Link
href="/contactez-nous"
className="border-b-2 border-transparent transition-all duration-300 ease-in-out hover:border-white"
>
{t("contact")}
</Link>
</li>
</ul>
</div>
);
};
export default HamburgerMenu;
+31
View File
@@ -0,0 +1,31 @@
import { Dispatch, SetStateAction } from "react";
import { ResponseMessage } from "@/types";
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;
+33
View File
@@ -0,0 +1,33 @@
import { useEffect } from "react";
import { useSetAtom } from "jotai";
import L from "leaflet";
import { useMapEvent } from "react-leaflet";
import { mapBoundsAtom } from "@/app/atoms";
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;
+54
View File
@@ -0,0 +1,54 @@
import { useTranslations } from "next-intl";
import Link from "next-intl/link";
import Hamburger from "./Hamburger";
export default function Navbar() {
const t = useTranslations("Nav");
const links = [
{ title: t("tournaments"), route: "/tournois" },
{ title: t("about"), route: "/qui-sommes-nous" },
{ title: t("contact"), route: "/contactez-nous" },
];
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,30 @@
import { ReactNode } from "react";
import { AbstractIntlMessages, NextIntlClientProvider } from "next-intl";
import "@/css/globals.css";
import Footer from "./Footer";
import Navbar from "./Navbar";
const TestableLayout = ({
children,
locale,
messages,
}: {
children: ReactNode;
locale: string;
messages: AbstractIntlMessages;
}) => {
return (
<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>
);
};
export default TestableLayout;
+48
View File
@@ -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
fill-rule="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,54 @@
import React from "react";
import { format } from "date-fns";
import { enGB, fr } from "date-fns/locale";
import { useLocale } from "next-intl";
import { ReactDatePickerCustomHeaderProps } from "react-datepicker";
import { IoChevronBack, IoChevronForward } from "react-icons/io5";
import { twMerge } from "tailwind-merge";
const chevronClasses = {
chevronRoot: "h-4 w-4 dark:text-white",
chevronClassDisabled: "!text-neutral-500",
};
export const DatePickerCustomHeader = ({
date,
decreaseMonth,
increaseMonth,
prevMonthButtonDisabled,
nextMonthButtonDisabled,
}: ReactDatePickerCustomHeaderProps) => {
// Bit of a hack. inputRef doesn't work because DatePicker doesn't correctly propagate props
const locale = useLocale();
return (
<div className="mb-2 flex !w-full items-center justify-between border-b border-neutral-500 px-6 pb-4">
<button
onClick={decreaseMonth}
disabled={prevMonthButtonDisabled}
className={chevronClasses.chevronRoot}
>
<IoChevronBack
className={twMerge(
chevronClasses.chevronRoot,
prevMonthButtonDisabled && chevronClasses.chevronClassDisabled,
)}
/>
</button>
{format(date, "LLLL yyyy", { locale: locale === "fr" ? fr : enGB })}
<button
onClick={increaseMonth}
disabled={nextMonthButtonDisabled}
className={chevronClasses.chevronRoot}
>
<IoChevronForward
className={twMerge(
chevronClasses.chevronRoot,
nextMonthButtonDisabled && chevronClasses.chevronClassDisabled,
)}
/>
</button>
</div>
);
};
@@ -0,0 +1,65 @@
import React, { forwardRef } from "react";
import InputMask from "react-input-mask";
import { twMerge } from "tailwind-merge";
interface InputProps {
error?: boolean;
className?: string;
inputContainerClass?: string;
inputClass?: string;
mask?: string | (string | RegExp)[];
}
type AllProps = React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
> &
InputProps;
export const InputDatePicker = forwardRef<HTMLInputElement, AllProps>(
(
{
error,
className,
children,
inputContainerClass,
inputClass,
mask,
...props
},
inputRef,
) => {
return (
<div
className={twMerge(
"flex w-full content-center rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 ",
!error &&
"focus-within:border-primary-500 focus-within:ring-primary-500 dark:focus-within:border-primary-500 dark:focus-within:ring-primary-500",
error && "!border-orange-700 focus:!border-orange-700",
inputContainerClass,
)}
>
<InputMask
ref={inputRef as any}
mask={mask ?? ""}
className={twMerge(
"w-full border-none bg-transparent text-sm outline-none ring-0 focus:outline-none focus:ring-0 focus:ring-offset-0",
"text-gray-900 dark:text-white",
inputClass,
)}
onKeyDown={(e) => {
if (e.code === "Enter") {
e.stopPropagation();
}
}}
{...props}
/>
</div>
);
},
);
InputDatePicker.displayName = "InputDatePicker";
@@ -0,0 +1 @@
export * from "./InputDatePicker";
@@ -0,0 +1,129 @@
import React, { useRef } from "react";
import { getYear, isValid, parse } from "date-fns";
import fr from "date-fns/locale/fr";
import { get, range } from "lodash";
import { useLocale, useTranslations } from "next-intl";
import DatePicker from "react-datepicker";
import { registerLocale } from "react-datepicker";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "../Field";
import { InputDatePicker } from "./components";
import { DatePickerCustomHeader } from "./components/DatePickerCustomHeader";
registerLocale("fr", fr);
type DateFieldProps = FieldProps & {
maxDate?: Date;
minDate?: Date;
dateFormat?: string;
className?: string;
datePickerPopperClass?: string;
required?: boolean;
};
export const DateField = ({
minDate,
maxDate,
dateFormat = "dd/MM/yyyy",
className,
datePickerPopperClass,
name,
...otherFieldProps
}: DateFieldProps) => {
const locale = useLocale();
const at = useTranslations("App");
const min = minDate ? minDate.getFullYear() : 1900;
const inputRef = useRef(null);
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = name && !!get(errors, name)?.message;
return (
<Field name={name} {...otherFieldProps}>
<div className={twMerge("relative flex w-full flex-col", className)}>
<Controller
control={form.control}
name={name}
render={({ field }) => (
<DatePicker
locale={locale}
closeOnScroll={true}
placeholderText={at("datePlaceholder")}
portalId="calendar-portal"
dateFormat={dateFormat}
disabledKeyboardNavigation={true}
formatWeekDay={(day: string) => (
<div className="flex h-8 flex-col items-center justify-center">
{day.slice(0, 3)}
</div>
)}
weekDayClassName={() =>
"text-xs h-8 w-8 flex-1 bg-gray-50 text-gray-900 dark:bg-gray-700 dark:text-white"
}
dayClassName={() =>
"text-xs h-8 w-8 flex-1 bg-gray-50 cursor-pointer hover:font-bold text-gray-900 dark:bg-gray-700 dark:text-white"
}
value={field.value}
selected={field.value}
onSelect={field.onChange}
onChange={field.onChange}
onChangeRaw={(e) => {
// Called when the user types in the input
if (e.currentTarget.value) {
const value = e.currentTarget.value;
const date = parse(value, at("dateParseFormat"), new Date());
if (
isValid(date) &&
date.getFullYear() >= min &&
maxDate &&
getYear(maxDate) >= getYear(date)
) {
field.onChange(date);
}
}
}}
popperPlacement="bottom-start"
popperClassName={twMerge(
"z-50 mt-[12px] rounded border",
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
datePickerPopperClass,
)}
showPopperArrow={false}
calendarClassName={twMerge(
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
)}
minDate={minDate}
showFullMonthYearPicker
maxDate={maxDate}
renderCustomHeader={(props) => (
<DatePickerCustomHeader {...props} />
)}
customInput={
<InputDatePicker
mask={at("dateMask")}
inputClass="p-0"
className="text-left"
ref={inputRef}
error={!!hasError}
/>
}
/>
)}
/>
</div>
</Field>
);
};
@@ -0,0 +1,21 @@
import { useTranslations } from "next-intl";
type ErrorMessageProps = {
errorMessage: string;
};
export const ErrorMessage = ({ errorMessage }: ErrorMessageProps) => {
const t = useTranslations();
type TranslationKey = Parameters<typeof t>[0];
return errorMessage !== undefined ? (
<div className="mt-2 font-medium text-orange-700">
<p>
{errorMessage.startsWith("FormValidation")
? t(errorMessage as TranslationKey)
: errorMessage}
</p>
</div>
) : null;
};
+68
View File
@@ -0,0 +1,68 @@
import { ReactNode } from "react";
import { get } from "lodash";
import { useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { ErrorMessage } from "./ErrorMessage";
import { Label } from "./Label";
export type FieldProps = {
name: string;
className?: string;
labelClassName?: string;
childrenWrapperClassName?: string;
label?: React.ReactNode;
hideErrorMessage?: boolean;
};
export const Field = (
props: Omit<FieldProps, "name"> & {
required?: boolean;
name?: string;
children: ReactNode;
},
) => {
const {
name,
className,
labelClassName,
childrenWrapperClassName,
label,
children,
required,
hideErrorMessage = false,
} = props;
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = name && !!get(errors, name)?.message;
return (
<div className={twMerge("flex w-full flex-col items-start", className)}>
{label ? (
<Label htmlFor={name} required={required} className={labelClassName}>
{label}
</Label>
) : null}
<div
className={twMerge(
"flex w-full",
label && "mt-2",
childrenWrapperClassName,
)}
>
{children}
</div>
{hideErrorMessage || !hasError ? null : (
<ErrorMessage errorMessage={String(get(errors, name)?.message)} />
)}
</div>
);
};
+31
View File
@@ -0,0 +1,31 @@
import { twMerge } from "tailwind-merge";
type LabelProps = React.DetailedHTMLProps<
React.LabelHTMLAttributes<HTMLLabelElement>,
HTMLLabelElement
> & {
required?: boolean;
className?: string;
tooltip?: React.ReactNode;
};
export const Label = ({
required,
className,
children,
tooltip,
...labelProps
}: LabelProps) => {
return (
<label
{...labelProps}
className={twMerge(
"flex items-center text-sm font-medium text-gray-900 dark:text-gray-300",
required && "after:ml-0.5 after:content-['*']",
className,
)}
>
<div>{children}</div>
</label>
);
};
@@ -0,0 +1,200 @@
import { Fragment, useRef } from "react";
import { Listbox, Transition } from "@headlessui/react";
import { useTranslations } from "next-intl";
import { Controller, useFormContext } from "react-hook-form";
import {
IoChevronDown,
IoCloseOutline,
IoSearchOutline,
} from "react-icons/io5";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export type SelectOption = {
value: string;
label: React.ReactNode;
selectedLabel?: React.ReactNode;
disabled?: boolean;
};
type SelectFieldProps = FieldProps & {
required?: boolean;
placeholder?: string;
noOptionsMessage?: string;
options: SelectOption[];
searchable?: boolean;
listboxClassName?: string;
dropdownClassName?: string;
searchValue?: string;
onChangeSearchValue?: (value: string) => void;
onOptionSelected?: (option: SelectOption) => void;
};
export const SelectField = ({
name,
label,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage = false,
required,
placeholder,
noOptionsMessage,
options,
searchable,
searchValue = "",
onChangeSearchValue,
onOptionSelected,
listboxClassName,
dropdownClassName,
}: SelectFieldProps) => {
const at = useTranslations("App");
const form = useFormContext();
// We need to keep track of the selected option to be able to continue to
// display it when the user searches for something else
const curOption = useRef<SelectOption | null>(null);
return (
<Field
{...{
name,
label,
required,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field: { onChange, value, name } }) => {
const selectedOption =
curOption.current?.value === value
? curOption.current
: options.find((option) => option.value === value);
return (
<Listbox
value={value ?? null}
name={name}
onChange={(value) => {
curOption.current =
options.find((option) => option.value === value) ?? null;
onChangeSearchValue?.("");
onChange(value);
onOptionSelected?.(curOption.current!);
}}
>
{({ open }) => (
<div className="relative w-full">
<Listbox.Button
className={twMerge(
"group flex w-full items-center justify-between rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm focus-within:border-primary-500 focus-within:ring-primary-500",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus-within:border-primary-500 dark:focus-within:ring-primary-500",
listboxClassName,
)}
>
<span className="block truncate pr-2 text-gray-900 dark:text-white">
{selectedOption?.selectedLabel ??
selectedOption?.label ??
placeholder ??
at("selectPlaceholder")}
</span>
<span className="pointer-events-none flex items-center pr-2">
<IoChevronDown
className="h-3 w-3 text-gray-900 dark:text-white"
aria-hidden="true"
/>
</span>
</Listbox.Button>
<Transition
as={Fragment}
show={open}
leave="transition ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div
className={twMerge(
"absolute z-10 mt-1 flex w-full flex-col overflow-y-hidden rounded border py-3 text-white focus:outline-none [&>ul]:outline-none",
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
dropdownClassName,
)}
>
<Listbox.Options className="flex max-h-[180px] flex-1 flex-col justify-stretch">
{searchable && (
<div className="mx-3 mb-4 flex h-[40px] w-auto flex-1 items-center justify-between rounded border px-4 dark:border-neutral-500 dark:bg-neutral-600 focus-within:dark:border-neutral-200">
<IoSearchOutline
width="16px"
className="h-4 w-4 flex-shrink-0 text-gray-900 dark:text-white"
/>
<input
className="w-full flex-1 border-none bg-transparent ring-0 focus:outline-none focus:ring-0 focus:ring-offset-0"
value={searchValue}
onChange={
onChangeSearchValue
? (e) => onChangeSearchValue(e.target.value)
: undefined
}
placeholder={at("searchPlaceholder")}
type="search"
/>
{searchValue.trim() !== "" && (
<button
className="flex h-4 w-4 flex-shrink-0 items-center justify-center"
type="button"
onClick={() => onChangeSearchValue?.("")}
>
<IoCloseOutline className="h-4 w-4 text-gray-900 transition-all duration-200 dark:text-white" />
</button>
)}
</div>
)}
{options.length === 0 ? (
<div className="w-full text-center">
{noOptionsMessage ?? at("noOptionsMessage")}
</div>
) : (
<div className="flex-1 overflow-scroll">
{options.map((option) => (
<Listbox.Option
key={option.value}
value={option.value}
disabled={option.disabled}
className={twMerge(
"w-full px-3 py-2 text-left",
!option.disabled &&
"hover:bg-primary-500 hover:text-white",
option.disabled && "opacity-50",
)}
>
{option.label}
</Listbox.Option>
))}
</div>
)}
</Listbox.Options>
</div>
</Transition>
</div>
)}
</Listbox>
);
}}
/>
</div>
</Field>
);
};
@@ -0,0 +1,60 @@
import React from "react";
import { Switch, SwitchProps } from "@headlessui/react";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export const SwitchField = (props: FieldProps & SwitchProps<"button">) => {
const {
name,
label,
disabled,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
...rest
} = props;
const form = useFormContext();
return (
<Field
{...{
name,
type: "checkbox",
label,
disabled,
className,
labelClassName,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field }) => (
<div className="flex h-[40px] items-center">
<Switch
checked={field.value}
onChange={field.onChange}
className={twMerge(
"relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none",
"ui-not-checked:bg-neutral-300 ui-not-checked:hover:bg-neutral-400",
"ui-not-checked:dark:bg-neutral-500 ui-not-checked:dark:hover:bg-neutral-600",
"ui-checked:bg-primary-500 ui-checked:hover:bg-primary-600",
)}
{...rest}
>
<span className="ui-checked:translate-x-[19px] ui-not-checked:translate-x-[3px] inline-block h-[14px] w-[14px] transform rounded-full bg-white transition-transform" />
</Switch>
</div>
)}
/>
</div>
</Field>
);
};
@@ -0,0 +1,88 @@
import React from "react";
import { get } from "lodash";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export const TextAreaField = (
props: FieldProps &
React.HTMLProps<HTMLTextAreaElement> & {
handleChanged?: (props: { name: string }) => void;
startIcon?: React.ReactNode;
},
) => {
const {
name,
label,
required,
disabled,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage = false,
startIcon,
handleChanged,
...rest
} = props;
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = !!get(errors, name)?.message;
return (
<Field
{...{
name,
label,
required,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field }) => (
<div className="relative">
{startIcon && (
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
{startIcon}
</div>
)}
<textarea
{...form.register(name, {
required,
})}
aria-required={required}
aria-invalid={hasError}
disabled={disabled}
className={twMerge(
"flex w-full content-center rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 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",
hasError && "!border-orange-700 focus:!border-orange-700",
disabled && "dark:bg-gray-50",
)}
{...rest}
onChange={(e) => {
field.onChange(e);
}}
value={field.value}
/>
</div>
)}
/>
</div>
</Field>
);
};
+111
View File
@@ -0,0 +1,111 @@
import React from "react";
import { get } from "lodash";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export const TextField = (
props: FieldProps &
React.HTMLProps<HTMLInputElement> & {
handleChanged?: (props: { name: string }) => void;
startIcon?: React.ReactNode;
},
) => {
const {
name,
type = "text",
label,
required,
disabled,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage = false,
startIcon,
handleChanged,
...rest
} = props;
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = !!get(errors, name)?.message;
const input = (value: string | number) => {
return typeof value === "number"
? isNaN(value)
? ""
: value.toString()
: value ?? "";
};
const output =
type === "number"
? (e: React.ChangeEvent<HTMLInputElement>) => {
const output = parseFloat(e.target.value);
return isNaN(output) ? 0 : output;
}
: (e: React.ChangeEvent<HTMLInputElement>) => e.target.value;
return (
<Field
{...{
name,
label,
required,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field }) => (
<div className="relative">
{startIcon && (
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
{startIcon}
</div>
)}
<input
type={type}
{...form.register(name, {
valueAsNumber: type === "number",
required,
})}
aria-required={required}
aria-invalid={hasError}
disabled={disabled}
className={twMerge(
"flex w-full content-center rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 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",
hasError && "!border-orange-700 focus:!border-orange-700",
disabled && "dark:bg-gray-50",
startIcon && "pl-10",
)}
{...rest}
onChange={(e) => {
field.onChange(output(e));
}}
value={input(field.value)}
onBlur={() => {
if (handleChanged) handleChanged({ name });
}}
/>
</div>
)}
/>
</div>
</Field>
);
};
+103
View File
@@ -0,0 +1,103 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import InfoMessage from "@/app/[locale]/components/InfoMessage";
import { handleEmailSubmit } from "@/handlers/formHandlers";
import useContactForm from "@/hooks/useContactForm";
const ContactForm = () => {
const t = useTranslations("Contact");
const { values, handleChange, resetForm } = useContactForm();
const [isSending, setIsSending] = useState(false);
const [responseMessage, setResponseMessage] = useState({
isSuccessful: false,
message: "",
});
return (
<>
<form
onSubmit={(e) =>
handleEmailSubmit(
e,
t,
setIsSending,
setResponseMessage,
values,
resetForm,
)
}
className="space-y-8"
>
<div>
<label
htmlFor="email"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("emailLabel")}
</label>
<input
value={values.email}
onChange={handleChange}
type="email"
id="email"
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("emailPlaceholder")}
required
data-test="email-input"
/>
</div>
<div>
<label
htmlFor="subject"
className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300"
>
{t("subjectLabel")}
</label>
<input
value={values.subject}
onChange={handleChange}
type="text"
id="subject"
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("subjectPlaceholder")}
required
data-test="subject-input"
/>
</div>
<div className="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
value={values.message}
onChange={handleChange}
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")}
data-test="message-input"
required
></textarea>
</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"
data-test="submit-button"
>
{isSending ? t("sending") : t("sendButton")}
</button>
<InfoMessage responseMessage={responseMessage} />
</form>
</>
);
};
export default ContactForm;
+24
View File
@@ -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>
);
}
+71
View File
@@ -0,0 +1,71 @@
import { ReactNode } from "react";
import { NextIntlClientProvider, useLocale } 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 Footer from "./components/Footer";
import Navbar from "./components/Navbar";
import Providers from "./providers";
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}`}>
<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>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { useTranslations } from "next-intl";
import Image from "next/image";
import Link from "next/link";
import bgImage from "@/public/images/map-bg.jpg";
export default function Home() {
const t = useTranslations("Home");
return (
<header className="relative mb-20 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) => (
<Link href="http://www.echecs.asso.fr/" target="_blank">
<abbr title="Fédération Française des Échecs">{chunks}</abbr>
</Link>
),
})}
</h3>
<Link
href="/tournois"
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>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { getFetch, httpBatchLink, loggerLink } from "@trpc/client";
import superjson from "superjson";
import { trpc } from "@/utils/trpc";
export const TrpcProvider = ({ children }: { children: React.ReactNode }) => {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: { queries: { staleTime: 5000 } },
}),
);
const url = "/api/trpc";
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
loggerLink({
enabled: () => true,
}),
httpBatchLink({
url,
fetch: async (input, init?) => {
const fetch = getFetch();
return fetch(input, {
...init,
credentials: "include",
});
},
}),
],
transformer: superjson,
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</trpc.Provider>
);
};
+16
View File
@@ -0,0 +1,16 @@
"use client";
import { Provider } from "jotai";
import { useDynamicViewportUnits } from "@/hooks/useDynamicViewportUnits";
import { TrpcProvider } from "./TrpcProvider";
export default function Providers({ children }: { children: React.ReactNode }) {
useDynamicViewportUnits();
return (
<Provider>
<TrpcProvider>{children}</TrpcProvider>
</Provider>
);
}
+122
View File
@@ -0,0 +1,122 @@
import { useTranslations } from "next-intl";
import Link from "next-intl/link";
export default function About() {
const t = useTranslations("About");
return (
<section className="grid place-items-center bg-white pb-20 dark:bg-gray-800">
<div className="max-w-5xl px-4 py-8 lg:py-16">
<h2
className="mb-8 text-center text-4xl font-extrabold tracking-tight text-gray-900 dark:text-white"
data-test="header2"
>
{t("title")}
</h2>
<p className="mb-4 text-center font-light text-gray-500 dark:text-gray-400 md:text-xl">
{t("p1")}
</p>
<p className="mb-4 text-center font-light text-gray-500 dark:text-gray-400 md:text-xl">
{t.rich("p2", {
homeLink: (chunks) => (
<Link href="/" className="text-primary-600">
{chunks}
</Link>
),
})}
</p>
<p className="mb-4 text-center font-light text-gray-500 dark:text-gray-400 md:text-xl">
{t("p3")}
</p>
<h3
className="mb-4 mt-8 text-center text-2xl font-extrabold tracking-tight text-gray-900 dark:text-white"
data-test="header2"
>
{t("thanksTitle")}
</h3>
<ul className="mb-4 text-center text-primary-600">
<li>
<Link href="https://github.com/timothyarmes" target="_blank">
timothyarmes
</Link>
</li>
<li>
<Link href="https://github.com/AlvaroNW" target="_blank">
AlvaroNW
</Link>
</li>
<li>
<Link href="https://github.com/Florifourchette" target="_blank">
Florifourchette
</Link>
</li>
</ul>
<h3
className="mb-4 mt-8 text-center text-2xl font-extrabold tracking-tight text-gray-900 dark:text-white"
data-test="header2"
>
{t("techTitle")}
</h3>
<p className="mb-4 text-center font-light text-gray-500 dark:text-gray-400 md:text-xl">
{t.rich("techInfo", {
homeLink: (chunks) => (
<Link href="/" className="text-primary-600">
{chunks}
</Link>
),
})}
</p>
<ul className="mx-auto mb-4 flex max-w-lg justify-around text-primary-600">
<li>
<Link href="https://nextjs.org/" target="_blank">
NextJS
</Link>
</li>
<li>
<Link href="#" target="_blank">
Typescript
</Link>
</li>
<li>
<Link href="https://tailwindcss.com/" target="_blank">
Tailwind
</Link>
</li>
<li>
<Link href="https://mongodb.com/" target="_blank">
MongoDB
</Link>
</li>
</ul>
<p className="mb-4 text-center font-light text-gray-500 dark:text-gray-400 md:text-xl">
{t("techWith")}
</p>
<ul className="mx-auto mb-8 flex max-w-md justify-around text-primary-600">
<li>
<Link href="https://leafletjs.com/" target="_blank">
Leaflet
</Link>
</li>
<li>
<Link href="https://nodemailer.com/" target="_blank">
Nodemailer
</Link>
</li>
</ul>
<p className="text-center font-light text-gray-500 dark:text-gray-400 md:text-xl">
{t.rich("contribInfo", {
link: (chunks) => (
<Link
href="https://github.com/TheRealOwenRees/echecsfrance"
target="_blank"
className="text-primary-600"
>
{chunks}
</Link>
),
})}
</p>
</div>
</section>
);
}
+63
View File
@@ -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 "@/app/atoms";
import { TimeControlColours } from "@/app/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,39 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { FaArrowUp } from "react-icons/fa";
import { handleScrollToTop } from "@/handlers/scrollHandlers";
import { useBreakpoint } from "@/hooks/tailwind";
import { ScrollableElement } from "@/types";
const ScrollToTopButton = () => {
const scrollToTopElementRef = useRef<ScrollableElement | null>(null);
const isLgScreen = useBreakpoint("lg");
// determine scrollable element based on screen size - window or div
useEffect(() => {
isLgScreen
? (scrollToTopElementRef.current =
document.getElementById("tournament-table"))
: (scrollToTopElementRef.current = window);
}, [isLgScreen]);
const scrollToTopButtonClass = isLgScreen
? "absolute bottom-0 right-3 p-10"
: "fixed bottom-20 right-3 py-10";
return (
<button
className={`${scrollToTopButtonClass} z-10 text-2xl text-primary-900 dark:text-white`}
data-test="scroll-to-top-button"
>
<FaArrowUp
onClick={() => handleScrollToTop(scrollToTopElementRef.current)}
/>
</button>
);
};
export default ScrollToTopButton;
+53
View File
@@ -0,0 +1,53 @@
import { useAtom } from "jotai/index";
import { useTranslations } from "next-intl";
import { IoCloseOutline } from "react-icons/io5";
import { searchStringAtom } from "@/app/atoms";
const SearchBar = () => {
const t = useTranslations("Tournaments");
const [searchString, setSearchString] = useAtom(searchStringAtom);
return (
<div className="bg-white dark:bg-gray-800">
<label htmlFor="table-search" className="sr-only">
{t("searchLabel")}
</label>
<div className="relative mt-1">
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
<svg
className="h-5 w-5 text-gray-500 dark:text-gray-400"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
clipRule="evenodd"
></path>
</svg>
</div>
{searchString !== "" && (
<div className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-900 dark:text-white">
<button onClick={() => setSearchString("")}>
<IoCloseOutline className="h-5 w-5" />
</button>
</div>
)}
<input
type="search"
id="table-search"
className="block rounded-lg border border-gray-300 bg-gray-50 p-2.5 px-10 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500"
placeholder={t("searchPlaceholder")}
value={searchString}
onChange={(e) => setSearchString(e.target.value)}
/>
</div>
</div>
);
};
export default SearchBar;
@@ -0,0 +1,48 @@
import { useAtom, useAtomValue } from "jotai";
import { useTranslations } from "next-intl";
import {
blitzAtom,
classicAtom,
otherAtom,
rapidAtom,
tournamentsAtom,
} from "@/app/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;
+307
View File
@@ -0,0 +1,307 @@
"use client";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useAtomValue, useSetAtom } from "jotai";
import L, { DomUtil, LatLngLiteral, Marker } 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 { FaAngleDoubleDown } from "react-icons/fa";
import { LayerGroup, MapContainer, TileLayer } from "react-leaflet";
import MarkerClusterGroup from "react-leaflet-cluster";
import MapEvents from "@/app/[locale]/components/MapEvents";
import {
debouncedHoveredListTournamentIdAtom,
filteredTournamentsByTimeControlAtom,
mapBoundsAtom,
normsOnlyAtom,
} from "@/app/atoms";
import { TimeControlColours } from "@/app/constants";
import { generatePieSVG } from "@/lib/pie";
import { TimeControl } from "@/types";
import Legend from "./Legend";
import TimeControlFilters from "./TimeControlFilters";
import { TournamentMarker, TournamentMarkerRef } from "./TournamentMarker";
// Declare a class type that adds in methods etc. defined by leaflet.smooth_marker_bouncing
// to keep Typescript happy
declare class BouncingMarker extends Marker {
isBouncing(): boolean;
bounce(): void;
stopBouncing(): void;
_icon: HTMLElement;
_bouncingMotion?: {
bouncingAnimationPlaying: boolean;
};
}
const stopBouncingMarkers = () => {
const markers =
// @ts-ignore
Marker.prototype._orchestration.getBouncingMarkers() as BouncingMarker[];
markers.forEach((marker) => {
if (marker.isBouncing()) {
try {
marker.stopBouncing();
// The plugin keeps bouncing until the end of the animation. We want to stop it immediately
// An issue has been raised on the project (https://github.com/hosuaby/Leaflet.SmoothMarkerBouncing/issues/52), until then we have this hack.
// We remove the class and reset some internal state
DomUtil.removeClass(marker._icon, "bouncing");
if (marker?._bouncingMotion?.bouncingAnimationPlaying === true)
marker._bouncingMotion.bouncingAnimationPlaying = false;
} catch {}
}
});
};
export default function TournamentMap() {
const tournaments = useAtomValue(filteredTournamentsByTimeControlAtom);
const normsOnly = useAtomValue(normsOnlyAtom);
const setMapBounds = useSetAtom(mapBoundsAtom);
const hoveredListTournamentId = useAtomValue(
debouncedHoveredListTournamentIdAtom,
);
const markerRefs = useRef<Record<string, TournamentMarkerRef>>({});
const clusterRef = useRef<L.MarkerClusterGroup | null>(null);
const expandedClusterMarkerRef = useRef<L.MarkerCluster | null>(null);
const filteredTournaments = useMemo(
() => tournaments.filter((t) => (normsOnly ? t.norm : true)),
[normsOnly, tournaments],
);
const groupedTournaments = groupBy(filteredTournaments, (t) => t.groupId);
const center: LatLngLiteral = { lat: 47.0844, lng: 2.3964 };
const onScrollToTable = () => {
const tournamentTable = document.getElementById("tournament-table");
tournamentTable?.scrollIntoView({ behavior: "smooth" });
};
const expandAndBounceIfNeeded = useCallback(() => {
if (hoveredListTournamentId) {
const tournament = filteredTournaments.find(
(t) => t.id === hoveredListTournamentId,
);
if (tournament) {
const markerRef = markerRefs.current[tournament.groupId];
if (markerRef) {
if (clusterRef.current) {
const visibleMarker = clusterRef.current.getVisibleParent(
markerRef.getMarker(),
);
if (!visibleMarker) return;
// @ts-ignore
if (visibleMarker.__proto__ === L.MarkerCluster.prototype) {
// This is a cluster icon, we expand it.
const clusterMarker = visibleMarker as L.MarkerCluster;
if (
expandedClusterMarkerRef.current &&
expandedClusterMarkerRef.current !== clusterMarker
) {
expandedClusterMarkerRef.current.unspiderfy();
}
clusterMarker.spiderfy();
// Sometimes there marker that's still bouncing from the last time the group was expanded.
// We stop it quickly.
setTimeout(() => {
stopBouncingMarkers();
}, 50);
} else {
// This is a standard marker, we bounce it.
const marker = visibleMarker as BouncingMarker;
if (!marker.isBouncing()) {
stopBouncingMarkers();
markerRef.bounce();
}
}
return true;
}
}
}
}
stopBouncingMarkers();
return false;
}, [filteredTournaments, hoveredListTournamentId]);
const onSpiderified = useCallback(
(e: L.MarkerClusterSpiderfyEvent) => {
// Once expanded, bounce the appropriate marker
if (hoveredListTournamentId) {
const tournament = filteredTournaments.find(
(t) => t.id === hoveredListTournamentId,
);
if (!tournament) return;
expandedClusterMarkerRef.current = e.cluster;
const markerRef = markerRefs.current[tournament.groupId];
if (markerRef && e.markers.includes(markerRef.getMarker())) {
stopBouncingMarkers();
markerRef.bounce();
}
}
},
[filteredTournaments, hoveredListTournamentId],
);
const onUnSpiderified = useCallback(
(e: L.MarkerClusterSpiderfyEvent) => {
if (expandedClusterMarkerRef.current === e.cluster)
expandedClusterMarkerRef.current = null;
// Once closed, we can expand the next group if needed
expandAndBounceIfNeeded();
},
[expandAndBounceIfNeeded],
);
useEffect(() => {
const ref = clusterRef.current;
if (clusterRef.current) {
clusterRef.current.on("spiderfied", onSpiderified);
clusterRef.current.on("unspiderfied", onUnSpiderified);
}
return () => {
if (ref) {
ref.off("spiderfied", onSpiderified);
ref.off("unspiderfied", onUnSpiderified);
}
};
}, [onSpiderified, onUnSpiderified]);
useEffect(() => {
// Expand/contract as hoveredListTournamentId changes
if (expandAndBounceIfNeeded()) return;
if (expandedClusterMarkerRef.current)
expandedClusterMarkerRef.current.unspiderfy();
}, [expandAndBounceIfNeeded, hoveredListTournamentId]);
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 = useMemo(
() =>
Object.values(groupedTournaments).map((tournamentGroup) => {
const { groupId } = tournamentGroup[0];
return (
<TournamentMarker
ref={(ref) => {
markerRefs.current[groupId] = ref!;
}}
key={groupId}
tournamentGroup={tournamentGroup}
/>
);
}),
[groupedTournaments],
);
return (
<section id="tournament-map" className="flex h-content flex-col">
<div className="p-3 lg:hidden">
<TimeControlFilters />
</div>
<MapContainer
center={center}
zoom={5}
scrollWheelZoom={false}
style={{
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"
/>
<Legend />
<LayerGroup>
<MarkerClusterGroup
ref={clusterRef}
chunkedLoading
iconCreateFunction={createClusterCustomIcon}
maxClusterRadius={40}
showCoverageOnHover={false}
spiderfyOnMaxZoom
>
{markers}
</MarkerClusterGroup>
</LayerGroup>
$
</MapContainer>
<div className="flex items-center justify-center lg:hidden">
<button
className="p-3 text-primary-900 dark:text-white"
onClick={onScrollToTable}
>
<FaAngleDoubleDown />
</button>
</div>
</section>
);
}
+117
View File
@@ -0,0 +1,117 @@
"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 { debouncedHoveredMapTournamentGroupIdAtom } from "@/app/atoms";
import { TimeControlColours } from "@/app/constants";
import type { BouncingMarker } from "@/leafletTypes";
import { Tournament } from "@/types";
export type TournamentMarkerRef = {
getMarker: () => L.Marker<any>;
bounce: () => void;
};
type TournamentMarkerProps = {
tournamentGroup: Tournament[];
} & Omit<MarkerProps, "position">;
export const TournamentMarker = forwardRef<
TournamentMarkerRef,
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 setHoveredMapTournamentGroupId = useSetAtom(
debouncedHoveredMapTournamentGroupIdAtom,
);
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: () => setHoveredMapTournamentGroupId(groupId),
mouseout: () => setHoveredMapTournamentGroupId(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";
+176
View File
@@ -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 {
debouncedHoveredListTournamentIdAtom,
debouncedHoveredMapTournamentGroupIdAtom,
filteredTournamentsListAtom,
hoveredMapTournamentGroupIdAtom,
normsOnlyAtom,
syncVisibleAtom,
} from "@/app/atoms";
import { useBreakpoint } from "@/hooks/tailwind";
import ScrollToTopButton from "./ScrollToTopButton";
import SearchBar from "./SearchBar";
import TimeControlFilters from "./TimeControlFilters";
export default function TournamentTable() {
const t = useTranslations("Tournaments");
const at = useTranslations("App");
const filteredTournaments = useAtomValue(filteredTournamentsListAtom);
const [syncVisible, setSyncVisible] = useAtom(syncVisibleAtom);
const [normsOnly, setNormsOnly] = useAtom(normsOnlyAtom);
const hoveredMapTournamentGroupId = useAtomValue(
hoveredMapTournamentGroupIdAtom,
);
const debouncedHoveredMapTournamentGroupId = useAtomValue(
debouncedHoveredMapTournamentGroupIdAtom,
);
const setHoveredListTournamentId = useSetAtom(
debouncedHoveredListTournamentIdAtom,
);
const isLg = useBreakpoint("lg");
useEffect(() => {
if (!isLg || debouncedHoveredMapTournamentGroupId === null) return;
const tournamentRow = document.querySelector(
`[data-group-id="${debouncedHoveredMapTournamentGroupId}"]`,
);
tournamentRow?.scrollIntoView({ behavior: "smooth" });
}, [debouncedHoveredMapTournamentGroupId, isLg]);
return (
<section
className="tournament-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="tournament-table"
data-test="tournament-table-div"
>
<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"
data-test="tournament-table"
>
<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"></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={() => setHoveredListTournamentId(tournament.id)}
onMouseLeave={() => setHoveredListTournamentId(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",
hoveredMapTournamentGroupId === 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 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">
<a href={tournament.url} target="_blank">
<FaExternalLinkAlt />
</a>
</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>
);
}
@@ -0,0 +1,40 @@
"use client";
import { useHydrateAtoms } from "jotai/utils";
import dynamic from "next/dynamic";
import LoadingMap from "@/app/[locale]/components/LoadingMap";
import { tournamentsAtom } from "@/app/atoms";
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>
);
}
+113
View File
@@ -0,0 +1,113 @@
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,
};
});
} catch (error) {
errorLog(error);
throw new Error("Error fetching tournament data");
}
};
export default async function Tournaments() {
const tournaments = await getTournaments();
return <TournamentsDisplay tournaments={tournaments} />;
}