Update next-intl (and other packages), internationalize URLs

This commit is contained in:
Timothy Armes
2023-10-10 19:48:13 +02:00
committed by Owen Rees
parent 44bfe17c8f
commit effb912641
32 changed files with 902 additions and 939 deletions
+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,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;
@@ -0,0 +1,98 @@
"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 "@/app/atoms";
import { TimeControlColours } from "@/app/constants";
import { Map, MapMarker } from "@/components/Map";
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 "@/app/atoms";
import { TimeControlColours } from "@/app/constants";
import type { MarkerRef } from "@/components/Map";
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 "@/app/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 "@/app/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>
);
}
+114
View File
@@ -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} />;
}