mirror of
https://github.com/TheRealOwenRees/echecsfrance.git
synced 2026-07-23 04:26:57 +00:00
Save and use user's locale preference
This commit is contained in:
@@ -1,12 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useSetAtom } from "jotai";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useParams } from "next/navigation";
|
||||
import { FaGithub, FaRegEnvelope } from "react-icons/fa";
|
||||
import { MdOutlinePrivacyTip } from "react-icons/md";
|
||||
|
||||
import { burgerMenuIsOpenAtom } from "@/atoms";
|
||||
import { setUserLocale } from "@/server/setUserLocale";
|
||||
import { Link, usePathname, useRouter } from "@/utils/routing";
|
||||
|
||||
import ThemeSwitcher from "./ThemeSwitcher";
|
||||
@@ -17,14 +19,19 @@ export default function Footer() {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const params = useParams();
|
||||
const { status } = useSession();
|
||||
|
||||
const changeLanguage = (lang: string) => {
|
||||
// Store the user's locale preference if they're authenticated
|
||||
if (status === "authenticated") setUserLocale(lang);
|
||||
|
||||
// Redirect to the same page with the new locale
|
||||
router.push({ pathname, params: params as any }, { locale: lang });
|
||||
};
|
||||
|
||||
return (
|
||||
<footer
|
||||
className="fixed bottom-0 z-30 flex h-12 w-[100vw] flex-col items-center justify-center justify-items-center bg-primary-600 px-5 py-2 text-white dark:bg-gray-700"
|
||||
className="fixed bottom-0 z-[1000] flex h-12 w-[100vw] flex-col items-center justify-center justify-items-center bg-primary-600 px-5 py-2 text-white dark:bg-gray-700"
|
||||
data-test="footer"
|
||||
>
|
||||
<div
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Inter, Julius_Sans_One } from "next/font/google";
|
||||
import { notFound } from "next/navigation";
|
||||
import Script from "next/script";
|
||||
|
||||
import { LocaleChecker } from "@/components/LocaleChecker";
|
||||
import "@/css/globals.css";
|
||||
import Providers from "@/providers";
|
||||
|
||||
@@ -70,9 +71,11 @@ export default async function RootLayout({
|
||||
<body>
|
||||
<Providers>
|
||||
<NextIntlClientProvider locale={locale} messages={messages}>
|
||||
<div className="bg-white font-sans leading-normal tracking-normal dark:bg-gray-800">
|
||||
{children}
|
||||
</div>
|
||||
<LocaleChecker>
|
||||
<div className="bg-white font-sans leading-normal tracking-normal dark:bg-gray-800">
|
||||
{children}
|
||||
</div>
|
||||
</LocaleChecker>
|
||||
|
||||
<Footer />
|
||||
</NextIntlClientProvider>
|
||||
|
||||
@@ -31,4 +31,12 @@ export const {
|
||||
pages: {
|
||||
signIn: "/auth/sign-in",
|
||||
},
|
||||
|
||||
callbacks: {
|
||||
session: async ({ session, user }) => {
|
||||
// Add the user's local to the session oject
|
||||
session.user.locale = user.locale;
|
||||
return session;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useLocale } from "next-intl";
|
||||
import { useParams } from "next/navigation";
|
||||
|
||||
import { setUserLocale } from "@/server/setUserLocale";
|
||||
import { usePathname, useRouter } from "@/utils/routing";
|
||||
|
||||
type LocaleCheckerProps = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
export const LocaleChecker = ({ children }: LocaleCheckerProps) => {
|
||||
const { data: sessionData, status, update } = useSession();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const params = useParams();
|
||||
const locale = useLocale();
|
||||
|
||||
const userLocale = sessionData?.user?.locale;
|
||||
|
||||
useEffect(() => {
|
||||
// If the user preference is not set, we set it to the current locale
|
||||
if (status === "authenticated" && userLocale === undefined) {
|
||||
setUserLocale(locale);
|
||||
}
|
||||
|
||||
// If the user is authenticated and has a preferred locale that is different from the user's locale,
|
||||
// then we update redirect to the user's preference
|
||||
if (
|
||||
status === "authenticated" &&
|
||||
userLocale !== undefined &&
|
||||
userLocale !== locale
|
||||
) {
|
||||
router.push({ pathname, params: params as any }, { locale: userLocale });
|
||||
}
|
||||
}, [locale, sessionData, status]);
|
||||
|
||||
// To avoid flickering, we don't render the children until we have the user's locale
|
||||
if (status === "loading") return null;
|
||||
if (
|
||||
status === "authenticated" &&
|
||||
userLocale !== undefined &&
|
||||
userLocale !== locale
|
||||
)
|
||||
return null;
|
||||
|
||||
return children;
|
||||
};
|
||||
@@ -34,8 +34,6 @@ export const SignInForm = ({ callbackPath }: SignInFormProps) => {
|
||||
message: "",
|
||||
});
|
||||
|
||||
console.log(path);
|
||||
|
||||
const form = useForm<SignInFormValues>({
|
||||
resolver: zodResolver(signInSchema),
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
"elo": "Calculette Elo",
|
||||
"signIn": "Se connecter",
|
||||
"signOut": "Se déconnecter",
|
||||
"myZones": "Mes Régions",
|
||||
"myZones": "Vos Régions",
|
||||
"deleteAccount": "Supprimer le compte"
|
||||
},
|
||||
|
||||
@@ -220,16 +220,16 @@
|
||||
|
||||
"Zones": {
|
||||
"title": "Vos régions",
|
||||
"info": "Vous pouvez définir des zones personnalisées pour recevoir des notifications par e-mail pour les tournois dans ces zones. Ces zones peuvent aussi être utiliser pour filtrer les tournois sur la carte.",
|
||||
"info": "Vous pouvez définir des régions personnalisées pour recevoir des notifications par e-mail pour les tournois dans ces zones. Ces régions peuvent aussi être utiliser pour filtrer les tournois sur la carte.",
|
||||
"logonRequired": "Vous devez être connecté pour accéder à cette fonctionnalité afin que nous puissions stocker vos régions personnalisées. Vous n'avez pas besoin de créer un compte, connectez-vous simplement avec votre adresse e-mail et nous vous enverrons un lien.",
|
||||
|
||||
"noNotifications": "Vous n'avez pas activé les notifications par email pour cette région.",
|
||||
"withNotifications": "Vous allez recevoir des notifications par e-mail pour les nouveaux tournois de cadences <b>{list}</b> dans cette région.",
|
||||
"addZoneButton": "Ajouter une région",
|
||||
|
||||
"yourZonesSelectGroupHeader": "Your Zones",
|
||||
"yourZonesSelectGroupHeader": "Vos régions",
|
||||
"ignoreMapOption": "Pas de filtre de région",
|
||||
"createZoneSelectOption": "Create a new zone",
|
||||
"createZoneSelectOption": "Créer une nouvelle région",
|
||||
|
||||
"createTitle": "Créer une nouvelle région",
|
||||
"editTitle": "Modifier région",
|
||||
@@ -237,7 +237,7 @@
|
||||
"zoneNameLabel": "Nom de la région",
|
||||
"zoneNamePlaceholder": "Votre nom pour cette région",
|
||||
"notificationsLabel": "Notifications",
|
||||
"notificationsInfo": "Vous pouvez choisir d'activer les notifications pour les cadences qui vous intéressent, et vous recevrez un e-mail lorsqu'un nouveau tournoi est ajouté dans cette zone.",
|
||||
"notificationsInfo": "Vous pouvez choisir d'activer les notifications pour les cadences qui vous intéressent, et vous recevrez un e-mail lorsqu'un nouveau tournoi est ajouté dans cette région.",
|
||||
|
||||
"createFailure": "Oups, quelque chose s'est mal passé. Veuillez réessayer.",
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { ObjectId } from "mongodb";
|
||||
|
||||
export type UserModel = {
|
||||
email: string;
|
||||
emailVerified?: Date;
|
||||
locale: string;
|
||||
};
|
||||
|
||||
export type VerificationModel = {
|
||||
identifier: string;
|
||||
expires: Date;
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
import mongoDB, { MongoClient } from "mongodb";
|
||||
import { User } from "next-auth";
|
||||
|
||||
import { TournamentModel } from "@/server/models/tournamentModel";
|
||||
import { UserModel, VerificationModel } from "@/server/models/userModel";
|
||||
import { ZoneModel } from "@/server/models/zoneModel";
|
||||
|
||||
import { ClubModel } from "./models/clubModel";
|
||||
@@ -9,9 +9,8 @@ import { ClubModel } from "./models/clubModel";
|
||||
export const collections: {
|
||||
tournaments?: mongoDB.Collection<TournamentModel>;
|
||||
clubs?: mongoDB.Collection<ClubModel>;
|
||||
users?: mongoDB.Collection<UserModel>;
|
||||
users?: mongoDB.Collection<User>;
|
||||
zones?: mongoDB.Collection<ZoneModel>;
|
||||
userVerificationTokens?: mongoDB.Collection<VerificationModel>;
|
||||
} = {};
|
||||
|
||||
if (!process.env.MONGODB_URI) {
|
||||
@@ -53,9 +52,6 @@ export async function dbConnect() {
|
||||
|
||||
const userData: mongoDB.Db = p.db("userData");
|
||||
collections.users = userData.collection("users");
|
||||
collections.userVerificationTokens = userData.collection(
|
||||
"userVerificationTokens",
|
||||
);
|
||||
collections.zones = userData.collection("zones");
|
||||
|
||||
const tournamentData: mongoDB.Db = p.db("tournamentsFranceDB");
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"use server";
|
||||
|
||||
import { ObjectId } from "mongodb";
|
||||
import { z } from "zod";
|
||||
|
||||
import { auth } from "@/auth";
|
||||
import { collections, dbConnect } from "@/server/mongodb";
|
||||
import { errorLog } from "@/utils/logger";
|
||||
|
||||
import { actionClient } from "./safeAction";
|
||||
|
||||
export const setUserLocale = actionClient
|
||||
.schema(z.string())
|
||||
.action(async (input) => {
|
||||
try {
|
||||
await dbConnect();
|
||||
|
||||
const user = await auth();
|
||||
if (!user?.user) {
|
||||
throw new Error("You must be logged update your locale");
|
||||
}
|
||||
|
||||
await collections.users!.findOneAndUpdate(
|
||||
{ _id: new ObjectId(user.user.id) },
|
||||
{ $set: { locale: input.parsedInput } },
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
errorLog(error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user