// Interface language on the server (PEP-98): the user's choice, else the cookie, else (only // before login) the browser's Accept-Language, else Russian. import { getUserLocaleSetting, setUserLocale } from "@peppa/core"; import { isLocale, LOCALE_COOKIE, localeFromAcceptLanguage, translator, type Locale, type Translator } from "@peppa/shared/i18n"; import { cookies, headers } from "next/headers"; import { cache } from "react"; import { currentUser } from "./auth"; import { db } from "./db"; export const getLocale = cache(async (): Promise => { const cookie = (await cookies()).get(LOCALE_COOKIE)?.value; const user = await currentUser(); if (user) { const own = await getUserLocaleSetting(db, user.id); if (own) return own; return isLocale(cookie) ? cookie : "ru"; } if (isLocale(cookie)) return cookie; return localeFromAcceptLanguage((await headers()).get("accept-language")) ?? "ru"; }); /** Translator for the current request: `const t = await getT(); t("Проекты")`. */ export async function getT(): Promise { return translator(await getLocale()); } export const localeCookieOptions = { sameSite: "lax" as const, path: "/", maxAge: 365 * 86400 }; /** * After login: a language picked on the login page (cookie) becomes the user's if they have * none yet; otherwise the user's language goes into the cookie. Returns the cookie to set. */ export async function adoptLocale(userId: number, cookieValue: string | undefined): Promise { const own = await getUserLocaleSetting(db, userId); if (own) return own === cookieValue ? null : own; if (isLocale(cookieValue)) await setUserLocale(db, userId, cookieValue); return null; }