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
+1 -6
View File
@@ -1,10 +1,5 @@
{ {
"extends": [ "extends": ["next", "next/core-web-vitals", "prettier"],
"next",
"next/core-web-vitals",
"plugin:react-hooks/recommended",
"prettier"
],
"globals": { "globals": {
"React": "readonly" "React": "readonly"
} }
+2
View File
@@ -1,5 +1,6 @@
{ {
"cSpell.words": [ "cSpell.words": [
"ajouter",
"approximative", "approximative",
"Armes", "Armes",
"colour", "colour",
@@ -30,6 +31,7 @@
"tailwindcss", "tailwindcss",
"tanstack", "tanstack",
"timothyarmes", "timothyarmes",
"tournoi",
"tournois", "tournois",
"trivago", "trivago",
"TRPC", "TRPC",
+10 -10
View File
@@ -1,11 +1,15 @@
"use client";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import Link from "next-intl/link";
import { FaGithub, FaRegEnvelope } from "react-icons/fa"; import { FaGithub, FaRegEnvelope } from "react-icons/fa";
import { Link, usePathname } from "@/utils/navigation";
import ThemeSwitcher from "./ThemeSwitcher"; import ThemeSwitcher from "./ThemeSwitcher";
export default function Footer() { export default function Footer() {
const t = useTranslations("Footer"); const t = useTranslations("Footer");
const pathname = usePathname();
return ( return (
<footer <footer
@@ -13,27 +17,23 @@ export default function Footer() {
data-test="footer" data-test="footer"
> >
<div className="flex items-center py-2 hover:[&_a]:opacity-80"> <div className="flex items-center py-2 hover:[&_a]:opacity-80">
<Link <a
href="https://github.com/TheRealOwenRees/echecsfrance" href="https://github.com/TheRealOwenRees/echecsfrance"
target="_blank" target="_blank"
aria-label={t("githubAria")} aria-label={t("githubAria")}
className="mr-4" className="mr-4"
> >
<FaGithub /> <FaGithub />
</Link> </a>
<Link <Link href="/contact-us" aria-label={t("contactAria")} className="mr-4">
href="/contactez-nous"
aria-label={t("contactAria")}
className="mr-4"
>
<FaRegEnvelope /> <FaRegEnvelope />
</Link> </Link>
<div className="mr-4 space-x-2 text-xs"> <div className="mr-4 space-x-2 text-xs">
<Link href="/" locale="fr"> <Link href={pathname} locale="fr">
FR FR
</Link> </Link>
<span>|</span> <span>|</span>
<Link href="/" locale="en"> <Link href={pathname} locale="en">
EN EN
</Link> </Link>
</div> </div>
+2 -2
View File
@@ -1,10 +1,10 @@
import { Dispatch, RefObject, SetStateAction, useRef, useState } from "react"; import { Dispatch, RefObject, SetStateAction, useRef, useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import Link from "next-intl/link";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import useHamburgerClose from "@/hooks/useHamburgerClose"; import useHamburgerClose from "@/hooks/useHamburgerClose";
import { Link } from "@/utils/navigation";
interface HamburgerMenuState { interface HamburgerMenuState {
menuVisible: boolean; menuVisible: boolean;
@@ -64,7 +64,7 @@ const HamburgerMenu = ({
<ul className="list-reset text-white"> <ul className="list-reset text-white">
<li className="py-5 text-center text-xl"> <li className="py-5 text-center text-xl">
<Link <Link
href="/tournois" href="/tournaments"
className="border-b-2 border-transparent transition-all duration-300 ease-in-out hover:border-white" className="border-b-2 border-transparent transition-all duration-300 ease-in-out hover:border-white"
> >
{t("tournaments")} {t("tournaments")}
+4 -3
View File
@@ -1,5 +1,6 @@
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import Link from "next-intl/link";
import { Link } from "@/utils/navigation";
import Hamburger from "./Hamburger"; import Hamburger from "./Hamburger";
@@ -7,10 +8,10 @@ export default function Navbar() {
const t = useTranslations("Nav"); const t = useTranslations("Nav");
const links = [ const links = [
{ title: t("tournaments"), route: "/tournois" }, { title: t("tournaments"), route: "/tournaments" },
{ title: t("clubs"), route: "/clubs" }, { title: t("clubs"), route: "/clubs" },
{ title: t("elo"), route: "/elo" }, { title: t("elo"), route: "/elo" },
]; ] as const;
return ( return (
<nav <nav
+9 -6
View File
@@ -1,11 +1,10 @@
"use client"; "use client";
import { useEffect, useRef, useState } from "react"; import { useEffect, useMemo } from "react";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { isEmpty, sortBy } from "lodash"; import { isEmpty, sortBy } from "lodash";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
@@ -14,6 +13,7 @@ import { Spinner } from "@/components/Spinner";
import { SelectField } from "@/components/form/SelectField"; import { SelectField } from "@/components/form/SelectField";
import { TextField } from "@/components/form/TextField"; import { TextField } from "@/components/form/TextField";
import { fetchTournamentResultsSchema } from "@/schemas"; import { fetchTournamentResultsSchema } from "@/schemas";
import { Link } from "@/utils/navigation";
import { trpc } from "@/utils/trpc"; import { trpc } from "@/utils/trpc";
import { KFactor } from "./KFactor"; import { KFactor } from "./KFactor";
@@ -36,7 +36,10 @@ export default function Elo() {
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const current = new URLSearchParams(Array.from(searchParams.entries())); const current = useMemo(
() => new URLSearchParams(Array.from(searchParams.entries())),
[searchParams],
);
const url = searchParams.get("url") ?? ""; const url = searchParams.get("url") ?? "";
const kFactorParam = searchParams.get("k"); const kFactorParam = searchParams.get("k");
@@ -132,7 +135,7 @@ export default function Elo() {
} }
}); });
return () => subscription.unsubscribe(); return () => subscription.unsubscribe();
}, [form.watch, kFactor, player]); }, [current, form, form.watch, kFactor, pathname, player, router]);
useEffect(() => { useEffect(() => {
// When the URL changes, we update the form values // When the URL changes, we update the form values
@@ -147,7 +150,7 @@ export default function Elo() {
if (kFactor !== form.getValues("kFactor")) { if (kFactor !== form.getValues("kFactor")) {
form.setValue("kFactor", form.getValues("kFactor")); form.setValue("kFactor", form.getValues("kFactor"));
} }
}, [searchParams, form]); }, [searchParams, form, url, player, kFactor]);
if (error) { if (error) {
console.error(error); console.error(error);
@@ -210,7 +213,7 @@ export default function Elo() {
? t(error.message as TranslationKey) ? t(error.message as TranslationKey)
: t.rich("unknownError", { : t.rich("unknownError", {
contact: (chunks) => ( contact: (chunks) => (
<Link className="underline" href="/contactez-nous"> <Link className="underline" href="/contact-us">
{chunks} {chunks}
</Link> </Link>
), ),
+2 -1
View File
@@ -8,9 +8,10 @@ import Script from "next/script";
import "@/css/globals.css"; import "@/css/globals.css";
import Providers from "../providers";
import Footer from "./components/Footer"; import Footer from "./components/Footer";
import Navbar from "./components/Navbar"; import Navbar from "./components/Navbar";
import Providers from "./providers";
const inter = Inter({ subsets: ["latin"], variable: "--font-inter" }); const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
const title = Julius_Sans_One({ const title = Julius_Sans_One({
+4 -4
View File
@@ -1,8 +1,8 @@
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import Image from "next/image"; import Image from "next/image";
import Link from "next/link";
import bgImage from "@/public/images/map-bg.jpg"; import bgImage from "@/public/images/map-bg.jpg";
import { Link } from "@/utils/navigation";
export default function Home() { export default function Home() {
const t = useTranslations("Home"); const t = useTranslations("Home");
@@ -25,14 +25,14 @@ export default function Home() {
<h3 className="mb-5 p-5 text-xl"> <h3 className="mb-5 p-5 text-xl">
{t.rich("how", { {t.rich("how", {
link: (chunks) => ( link: (chunks) => (
<Link href="http://www.echecs.asso.fr/" target="_blank"> <a href="http://www.echecs.asso.fr/" target="_blank">
<abbr title="Fédération Française des Échecs">{chunks}</abbr> <abbr title="Fédération Française des Échecs">{chunks}</abbr>
</Link> </a>
), ),
})} })}
</h3> </h3>
<Link <Link
href="/tournois" 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" 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")} {t("mapLink")}
+20 -19
View File
@@ -1,27 +1,28 @@
import { MetadataRoute } from "next"; import { MetadataRoute } from "next";
import { locales, pathnames } from "@/utils/navigation";
export default function sitemap(): MetadataRoute.Sitemap { export default function sitemap(): MetadataRoute.Sitemap {
return ["fr", "en"].flatMap((locale) => { return locales.flatMap((locale) => {
const prefix = `https://echecsfrance.com/${ const prefix = `https://echecsfrance.com${
locale === "fr" ? "" : `${locale}/` locale === "fr" ? "" : `/${locale}`
}`; }`;
return [
{ const paths = Object.keys(pathnames) as Array<keyof typeof pathnames>;
url: prefix,
return paths.map((pathname) => {
const route = pathnames[pathname];
if (typeof route === "string") {
return {
url: `${prefix}${route}`,
lastModified: new Date(), lastModified: new Date(),
}, };
{ }
url: `${prefix}tournois`,
return {
url: `${prefix}${route[locale]}`,
lastModified: new Date(), lastModified: new Date(),
}, };
{ });
url: `${prefix}qui-sommes-nous`,
lastModified: new Date(),
},
{
url: `${prefix}contactez-nous`,
lastModified: new Date(),
},
];
}); });
} }
@@ -19,7 +19,6 @@ export const DatePickerCustomHeader = ({
prevMonthButtonDisabled, prevMonthButtonDisabled,
nextMonthButtonDisabled, nextMonthButtonDisabled,
}: ReactDatePickerCustomHeaderProps) => { }: ReactDatePickerCustomHeaderProps) => {
// Bit of a hack. inputRef doesn't work because DatePicker doesn't correctly propagate props
const locale = useLocale(); const locale = useLocale();
return ( return (
@@ -11,9 +11,12 @@ interface InputProps {
mask?: string | (string | RegExp)[]; mask?: string | (string | RegExp)[];
} }
type AllProps = React.DetailedHTMLProps< type AllProps = Omit<
React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>, React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement HTMLInputElement
>,
"ref"
> & > &
InputProps; InputProps;
@@ -26,6 +29,7 @@ export const InputDatePicker = forwardRef<HTMLInputElement, AllProps>(
inputContainerClass, inputContainerClass,
inputClass, inputClass,
mask, mask,
...props ...props
}, },
inputRef, inputRef,
@@ -43,7 +47,7 @@ export const InputDatePicker = forwardRef<HTMLInputElement, AllProps>(
)} )}
> >
<InputMask <InputMask
ref={inputRef as any} inputRef={inputRef}
mask={mask ?? ""} mask={mask ?? ""}
className={twMerge( className={twMerge(
"w-full border-none bg-transparent text-sm outline-none ring-0 focus:outline-none focus:ring-0 focus:ring-offset-0", "w-full border-none bg-transparent text-sm outline-none ring-0 focus:outline-none focus:ring-0 focus:ring-offset-0",
+2 -3
View File
@@ -2,10 +2,9 @@ import React, { useRef } from "react";
import { getYear, isValid, parse } from "date-fns"; import { getYear, isValid, parse } from "date-fns";
import fr from "date-fns/locale/fr"; import fr from "date-fns/locale/fr";
import { get, range } from "lodash"; import { get } from "lodash";
import { useLocale, useTranslations } from "next-intl"; import { useLocale, useTranslations } from "next-intl";
import DatePicker from "react-datepicker"; import DatePicker, { registerLocale } from "react-datepicker";
import { registerLocale } from "react-datepicker";
import { import {
Controller, Controller,
FieldPath, FieldPath,
-3
View File
@@ -52,9 +52,6 @@ export const Field = <
children, children,
required, required,
hideErrorMessage = false, hideErrorMessage = false,
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- used to restrict the `name` prop type
control,
} = props; } = props;
const form = useFormContext<TFieldValues>(); const form = useFormContext<TFieldValues>();
+7 -5
View File
@@ -1,15 +1,17 @@
import createMiddleware from "next-intl/middleware"; import createMiddleware from "next-intl/middleware";
export default createMiddleware({ import { locales, pathnames } from "@/utils//navigation";
// A list of all locales that are supported
locales: ["fr", "en"],
// If this locale is matched, pathnames work without a prefix (e.g. `/tournois`) export default createMiddleware({
defaultLocale: "fr", defaultLocale: "fr",
locales,
pathnames,
localePrefix: "as-needed",
}); });
export const config = { export const config = {
// Skip all paths that should not be internationalized. This example skips certain folders // Skip all paths that should not be internationalized. This example skips certain folders
// such as "api", and all files with an extension (e.g. favicon.ico) // such as "api", and all files with an extension (e.g. favicon.ico)
matcher: ["/((?!api|_next|robots|.*\\..*).*)"], matcher: ["/((?!api|_next|robots|sitemap|.*\\..*).*)"],
}; };
+7 -6
View File
@@ -22,9 +22,9 @@
"@trpc/client": "^10.38.1", "@trpc/client": "^10.38.1",
"@trpc/react-query": "^10.38.1", "@trpc/react-query": "^10.38.1",
"@trpc/server": "^10.38.1", "@trpc/server": "^10.38.1",
"@types/node": "20.6.3", "@types/node": "^20.8.4",
"@types/react": "18.2.21", "@types/react": "^18.2.27",
"@types/react-dom": "18.2.7", "@types/react-dom": "^18.2.12",
"autoprefixer": "10.4.15", "autoprefixer": "10.4.15",
"date-fns": "^2.30.0", "date-fns": "^2.30.0",
"jotai": "^2.2.2", "jotai": "^2.2.2",
@@ -35,7 +35,7 @@
"lodash": "^4.17.21", "lodash": "^4.17.21",
"mongodb": "^6.1.0", "mongodb": "^6.1.0",
"next": "^13.4.12", "next": "^13.4.12",
"next-intl": "^3.0.0-beta.16", "next-intl": "3.0.0-rc.4",
"next-pwa": "^5.6.0", "next-pwa": "^5.6.0",
"nodemailer": "^6.9.4", "nodemailer": "^6.9.4",
"postcss": "8.4.28", "postcss": "8.4.28",
@@ -53,10 +53,11 @@
"superjson": "^1.13.1", "superjson": "^1.13.1",
"tailwind-merge": "^1.14.0", "tailwind-merge": "^1.14.0",
"tailwindcss": "3.3.3", "tailwindcss": "3.3.3",
"typescript": "5.2.2" "typescript": "5.2.2",
"zod": "^3.22.4"
}, },
"devDependencies": { "devDependencies": {
"@swc-jotai/react-refresh": "^0.0.8", "@swc-jotai/react-refresh": "^0.1.0",
"@tailwindcss/forms": "^0.5.4", "@tailwindcss/forms": "^0.5.4",
"@testing-library/jest-dom": "^6.1.2", "@testing-library/jest-dom": "^6.1.2",
"@testing-library/react": "^14.0.0", "@testing-library/react": "^14.0.0",
+1
View File
@@ -1,4 +1,5 @@
/** @type {import('tailwindcss').Config} */ /** @type {import('tailwindcss').Config} */
module.exports = { module.exports = {
darkMode: "class", darkMode: "class",
content: [ content: [
+32
View File
@@ -0,0 +1,32 @@
import {
Pathnames,
createLocalizedPathnamesNavigation,
} from "next-intl/navigation";
export const locales = ["fr", "en"] as const;
// The `pathnames` object holds pairs of internal
// and external paths, separated by locale.
export const pathnames = {
"/": "/",
"/clubs": "/clubs",
"/elo": "/elo",
"/tournaments": {
fr: "/tournois",
en: "/tournaments",
},
"/add-tournament": {
fr: "/ajouter-un-tournoi",
en: "/add-tournament",
},
"/contact-us": {
fr: "/contactez-nous",
en: "/contact-us",
},
} satisfies Pathnames<typeof locales>;
export const { Link, redirect, usePathname, useRouter, getPathname } =
createLocalizedPathnamesNavigation({ locales, pathnames });
+790 -865
View File
File diff suppressed because it is too large Load Diff