add: locale and i18n

This commit is contained in:
Mahyar Khanbolooki
2025-07-24 03:14:21 +03:30
parent b9d14478a1
commit 1b3fac2f43
38 changed files with 385 additions and 69 deletions
+9
View File
@@ -0,0 +1,9 @@
import 'server-only'
const dictionaries = {
en: () => import('@/dictionaries/en.json').then((module) => module.default),
fa: () => import('@/dictionaries/fa.json').then((module) => module.default),
}
export const getDictionary = async (locale: 'en' | 'fa') =>
dictionaries[locale]()
+49
View File
@@ -0,0 +1,49 @@
import { Metadata } from "next";
import "../globals.css";
import { ReactQueryProvider } from "@/components/providers/ReactQueryProvider";
import { notFound } from "next/navigation";
import i18nConfig from "../../../i18nConfig";
import initTranslations from '@/lib/i18n';
import TranslationsProvider from "@/components/utils/TranslationsProdiver";
export const metadata: Metadata = {
title: 'Dashboard',
description: 'Webapp dashboard'
}
const i18nNamespaces = ['auth'];
export default async function RootLayout({
children,
params,
}: Readonly<{
children: React.ReactNode;
params: { locale: string }
}>) {
const { locale } = await params;
if (!i18nConfig.locales.includes(locale)) {
notFound();
}
const { resources } = await initTranslations(locale, i18nNamespaces);
return (
<html lang={locale} className="h-svh overflow-hidden">
<body
dir={locale === 'fa' ? 'rtl' : 'ltr'}
className={`antialiased bg-background h-svh overflow-hidden`}
>
<ReactQueryProvider>
<TranslationsProvider
namespaces={i18nNamespaces}
locale={locale}
resources={resources}>
<div id="root" className="h-svh overflow-hidden">
{children}
</div>
</TranslationsProvider>
</ReactQueryProvider>
</body>
</html >
);
}
-31
View File
@@ -1,31 +0,0 @@
import { Metadata } from "next";
import "./globals.css";
import { ReactQueryProvider } from "@/components/providers/ReactQueryProvider";
export const metadata: Metadata = {
title: 'Dashboard',
description: 'Webapp dashboard'
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className="h-svh overflow-hidden">
<body
dir="rtl"
className={`antialiased bg-background h-svh overflow-hidden`}
>
<ReactQueryProvider>
<div id="root" className="h-svh overflow-hidden">
{children}
</div>
</ReactQueryProvider>
</body>
</html>
);
}
+1 -1
View File
@@ -15,7 +15,7 @@ function InputField({ onChange, htmlFor, labelText, children, valid = true, clas
return (
<div className={`${className} ${valid ? 'border-border' : 'border-invalid'} h-11 inline-flex relative border px-3 w-full rounded-normal group focus-within:border`}>
<label
className='absolute right-2 -top-3 px-2 bg-container text-[12px] text-foreground'
className='absolute start-2 -top-2.5 px-2 bg-container text-[12px] text-foreground'
htmlFor={htmlFor}>
{labelText}
</label>
@@ -0,0 +1,18 @@
'use client';
import { I18nextProvider } from 'react-i18next';
import initTranslations from '@/lib/i18n';
import { createInstance } from 'i18next';
export default function TranslationsProvider({
children,
locale,
namespaces,
resources
}) {
const i18n = createInstance();
initTranslations(locale, namespaces, i18n, resources);
return <I18nextProvider i18n={i18n}>{children}</I18nextProvider>;
}
@@ -1,8 +1,11 @@
'use client';
import Button from '@/components/button/PrimaryButton';
import InputField from '@/components/input/InputField';
import { AUTH_PAGE_ELEMENT } from '@/enums';
import Image from 'next/image';
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next';
type Props = {
onChange: React.ChangeEventHandler<HTMLInputElement>;
@@ -12,6 +15,7 @@ type Props = {
function StepEnterNumber({ onChange, pending, disabled, value }: Props) {
const [error, setError] = useState('');
const { t } = useTranslation();
const hasError = (e = error) => {
return e.trim().length > 0
@@ -21,12 +25,12 @@ function StepEnterNumber({ onChange, pending, disabled, value }: Props) {
let error = '';
if (value.length > 0) {
if (!/^09\d{7,9}$/.test(value)) {
error = 'فرمت اشتباه است';
error = t('Errors.PhoneNumberFormat');
}
}
setError(error);
}, [value])
}, [t, value])
return (
<>
@@ -41,9 +45,9 @@ function StepEnterNumber({ onChange, pending, disabled, value }: Props) {
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='w-full'>
<div className='pt-4' dir='rtl'>
<h6 className='text-lg font-bold'>ورود به سیستم</h6>
<p className='mt-3 text-[13px]'>برای ورود شماره همراه خود را وارد نمایید.</p>
<div className='pt-4'>
<h6 className='text-lg font-bold'>{t('Enter.Heading')}</h6>
<p className='mt-3 text-[13px]'>{t('Enter.Description')}</p>
</div>
<InputField
valid={!hasError()}
@@ -52,13 +56,13 @@ function StepEnterNumber({ onChange, pending, disabled, value }: Props) {
autoComplete='tel'
className='mt-10 w-full'
htmlFor={AUTH_PAGE_ELEMENT.INPUT_PHONE}
labelText='شماره همراه'
labelText={t('Enter.LabelPhoneNumber')}
value={value}
placeholder='09120000000'
onChange={onChange}
type='number' />
</div>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>بعدی</Button>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>{t('Enter.ButtonSubmit')}</Button>
</div>
</>
)
+12 -10
View File
@@ -4,6 +4,7 @@ import { AUTH_PAGE_ELEMENT, AUTH_PAGE_ELEMENT as AUTH_PAGE_ELEMENTS } from '@/en
import clsx from 'clsx';
import Image from 'next/image';
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next';
type Props = {
onChange: ((e: React.ChangeEvent<HTMLInputElement>) => void) & React.ChangeEventHandler<HTMLInputElement>;
@@ -17,6 +18,7 @@ type Props = {
function StepEnterOtp({ onChange, onClick, pending, disabled = false, value, phoneNumber, timerRunning, secondsLeft }: Props) {
const [error, setError] = useState('');
const { t } = useTranslation();
const hasError = (e = error) => {
return e.trim().length > 0
@@ -25,11 +27,11 @@ function StepEnterOtp({ onChange, onClick, pending, disabled = false, value, pho
useEffect(() => {
let error = '';
if (!/^\d{6}$/.test(value)) {
error = 'عبارت کامل نیست';
error = t('Errors.OTPFormat');
}
setError(error);
}, [value])
}, [t, value])
return (
<>
@@ -43,10 +45,10 @@ function StepEnterOtp({ onChange, onClick, pending, disabled = false, value, pho
priority
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='pt-4' dir='rtl'>
<div className='pt-4'>
{/* // TODO: add persian digits font */}
<h6 className='text-lg font-bold'>کد فعالسازی را وارد کنید</h6>
<p className='mt-3 text-[13px]'>کد ۶ رقمی ارسال شده به شماره {phoneNumber} را وارد نمایید.</p>
<h6 className='text-lg font-bold'>{t('OTP.Heading')}</h6>
<p className='mt-3 text-[13px]'>{t('OTP.Description').replace('{phoneNumber}', phoneNumber)}</p>
</div>
<div className='w-full flex justify-center items-center'>
<OTPInputField
@@ -64,11 +66,11 @@ function StepEnterOtp({ onChange, onClick, pending, disabled = false, value, pho
</div>
<div className='text-center w-full pt-6 text-xs'>
<div dir='rtl'>
<div>
{timerRunning ?
<div>{secondsLeft} ثانیه دیگر تا دریافت کد</div> :
<div>{t('OTP.TimerRunning').replace('{seconds}', String(secondsLeft))}</div> :
<div>
کد را دریافت نکردید؟
{t('OTP.TimerOut')}
<button
type='button'
disabled={pending}
@@ -77,13 +79,13 @@ function StepEnterOtp({ onChange, onClick, pending, disabled = false, value, pho
'px-1 transition-colors duration-200',
!pending ? 'text-primary cursor-pointer' : 'text-neutral-200 cursor-auto'
)} onClick={onClick}>
دوباره امتحان کنید
{t('OTP.TimerReset')}
</button>
</div>
}
</div>
</div>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>بعدی</Button>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>{t('OTP.ButtonSubmit')}</Button>
</div>
</>
)
@@ -4,6 +4,7 @@ import InputField from '@/components/input/InputField';
import { AUTH_PAGE_ELEMENT } from '@/enums';
import Image from 'next/image';
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next';
type Props = {
onChange: ((e: React.ChangeEvent<HTMLInputElement>) => void) & React.ChangeEventHandler<HTMLInputElement>;
@@ -16,6 +17,7 @@ type Props = {
function StepEnterPassword({ onChange, onClick, pending, disabled = false, value, passwordVisible, rememberMe }: Props) {
const [error, setError] = useState('');
const { t } = useTranslation();
const hasError = (e = error) => {
return e.trim().length > 0
@@ -25,12 +27,12 @@ function StepEnterPassword({ onChange, onClick, pending, disabled = false, value
let error = '';
if (value.length > 0) {
if (!/^.{6,}$/.test(value)) {
error = 'کلمه عبور باید شامل حداقل 6 کاراکتر باشد';
error = t('Errors.PasswordLength');
}
}
setError(error);
}, [value])
}, [t, value])
return (
<>
@@ -45,9 +47,9 @@ function StepEnterPassword({ onChange, onClick, pending, disabled = false, value
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='w-full'>
<div className='pt-4' dir='rtl'>
<h6 className='text-lg font-bold'>ورود به سیستم</h6>
<p className='mt-3 text-[13px]'>کلمه عبور خود را وارد نمایید.</p>
<div className='pt-4'>
<h6 className='text-lg font-bold'>{t('EnterPass.Heading')}</h6>
<p className='mt-3 text-[13px]'>{t('EnterPass.Description')}</p>
</div>
<InputField
valid={!hasError()}
@@ -56,7 +58,7 @@ function StepEnterPassword({ onChange, onClick, pending, disabled = false, value
autoComplete='current-password'
className='mt-10'
htmlFor={AUTH_PAGE_ELEMENT.INPUT_PASSWORD}
labelText='کلمه عبور'
labelText={t('EnterPass.LabelPass')}
value={value}
placeholder=''
onChange={onChange}
@@ -66,15 +68,19 @@ function StepEnterPassword({ onChange, onClick, pending, disabled = false, value
</button>
</InputField>
<div className='inline-flex justify-between items-center w-full pt-3'>
<button id={AUTH_PAGE_ELEMENT.RESET_PASSWORD} type='button' onClick={onClick} className='text-sm2 cursor-pointer'>بازیابی کلمه عبور</button>
<button id={AUTH_PAGE_ELEMENT.RESET_PASSWORD} type='button' onClick={onClick} className='text-sm2 cursor-pointer'>
{t('EnterPass.ButtonRecover')}
</button>
<div className='inline-flex justify-between items-center'>
{/* TODO: customize checkbox */}
<label htmlFor={AUTH_PAGE_ELEMENT.INPUT_REMEMBER_ME} className='text-sm2 px-2 py-0.5'>مرا به خاطر بسپار</label>
<label htmlFor={AUTH_PAGE_ELEMENT.INPUT_REMEMBER_ME} className='text-sm2 px-2 py-0.5'>
{t('EnterPass.LabelRememberance')}
</label>
<input name={AUTH_PAGE_ELEMENT.INPUT_REMEMBER_ME} className='h-4.5 w-4.5 checked:accent-primary' onChange={onChange} type='checkbox' checked={rememberMe} /></div>
</div>
</div>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>ورود به منو</Button>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>{t('EnterPass.ButtonSubmit')}</Button>
</div>
</>
)
@@ -4,6 +4,7 @@ import InputField from '@/components/input/InputField';
import { AUTH_PAGE_ELEMENT } from '@/enums';
import Image from 'next/image';
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next';
type Props = {
onChange: ((e: React.ChangeEvent<HTMLInputElement>) => void) & React.ChangeEventHandler<HTMLInputElement>;
@@ -19,6 +20,7 @@ type Props = {
function StepNewPassword({ isReset: reset = false, pending, disabled = false, onChange, onClick, value, repeatValue, passwordVisible, repeatPasswordVisible }: Props) {
const [error, setError] = useState('');
const [error2, setError2] = useState('');
const { t } = useTranslation();
const hasError = (e = error) => {
return e.trim().length > 0
@@ -29,20 +31,20 @@ function StepNewPassword({ isReset: reset = false, pending, disabled = false, on
let error2 = '';
if (value.length > 0) {
if (!/^.{6,}$/.test(value)) {
error = 'کلمه عبور باید شامل حداقل 6 کاراکتر باشد';
error = t('Errors.PasswordLength');
}
}
if (repeatValue.length > 0) {
if (!/^.{6,}$/.test(repeatValue)) {
error2 = 'کلمه عبور باید شامل حداقل 6 کاراکتر باشد';
error2 = t('Errors.PasswordLength');
} else if (repeatValue !== value) {
error2 = 'تکرار کلمه عبور مطابقت ندارد';
error2 = t('Errors.PasswordMatch');
}
}
setError(error);
setError2(error2);
}, [value, repeatValue])
}, [value, repeatValue, t])
return (
<>
@@ -57,11 +59,11 @@ function StepNewPassword({ isReset: reset = false, pending, disabled = false, on
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='w-full'>
<div className='pt-4' dir='rtl'>
<div className='pt-4'>
<h6 className='text-lg font-bold'>
{reset ? "تغییر کلمه عبور" : "انتخاب کلمه عبور"}
{reset ? t('NewPassword.HeadingResetPass') : t('NewPassword.HeadingCreatePass')}
</h6>
<p className='mt-3 text-[13px]'>کلمه عبور جدید باید ترکیبی از حروف بزرگ و کوچک و نشانه ها باشد مثل A126bdz@</p>
<p className='mt-3 text-[13px]'>{t('NewPassword.Description')}</p>
</div>
<InputField
valid={!hasError()}
@@ -69,7 +71,7 @@ function StepNewPassword({ isReset: reset = false, pending, disabled = false, on
autoComplete='new-password'
className='mt-10'
htmlFor={AUTH_PAGE_ELEMENT.INPUT_PASSWORD}
labelText='کلمه عبور'
labelText={t('NewPassword.LabelPass')}
value={value}
placeholder=''
onChange={onChange}
@@ -84,7 +86,7 @@ function StepNewPassword({ isReset: reset = false, pending, disabled = false, on
autoComplete='new-password'
className='mt-6'
htmlFor={AUTH_PAGE_ELEMENT.INPUT_PASSWORD_REPEAT}
labelText='تکرار کلمه عبور'
labelText={t('NewPassword.LabelRepeatPass')}
value={repeatValue}
placeholder=''
onChange={onChange}
@@ -94,7 +96,7 @@ function StepNewPassword({ isReset: reset = false, pending, disabled = false, on
</button>
</InputField>
</div>
<Button disabled={disabled || hasError() || hasError(error2) || value.length <= 0} pending={pending} type='submit'>ورود</Button>
<Button disabled={disabled || hasError() || hasError(error2) || value.length <= 0} pending={pending} type='submit'>{t('NewPassword.ButtonSubmit')}</Button>
</div>
</>
)
+41
View File
@@ -0,0 +1,41 @@
import { createInstance } from 'i18next';
import { initReactI18next } from 'react-i18next/initReactI18next';
import resourcesToBackend from 'i18next-resources-to-backend';
import i18nConfig from '../../i18nConfig';
export default async function initTranslations(
locale,
namespaces,
i18nInstance,
resources
) {
i18nInstance = i18nInstance || createInstance();
i18nInstance.use(initReactI18next);
if (!resources) {
i18nInstance.use(
resourcesToBackend(
(language, namespace) =>
import(`@/locales/${language}/${namespace}.json`)
)
);
}
await i18nInstance.init({
lng: locale,
resources,
fallbackLng: i18nConfig.defaultLocale,
supportedLngs: i18nConfig.locales,
defaultNS: namespaces[0],
fallbackNS: namespaces[0],
ns: namespaces,
preload: resources ? [] : i18nConfig.locales
});
return {
i18n: i18nInstance,
resources: { [locale]: i18nInstance.services.resourceStore.data[locale] },
t: i18nInstance.t
};
}
+39
View File
@@ -0,0 +1,39 @@
{
"Enter": {
"Heading": "Login",
"Description": "Please enter your mobile number to log in.",
"LabelPhoneNumber": "Mobile Number",
"ButtonSubmit": "Next"
},
"OTP": {
"Heading": "Enter Activation Code",
"Description": "Please enter the 6-digit code sent to the number {phoneNumber}.",
"Label": "",
"TimerRunning": "{seconds} seconds left to receive the code",
"TimerOut": "Didnt receive the code?",
"TimerReset": "Try again",
"ButtonSubmit": "Next"
},
"NewPassword": {
"HeadingCreatePass": "Choose Password",
"HeadingResetPass": "Change Password",
"Description": "The new password must be a combination of uppercase and lowercase letters and symbols, like A126bdz@",
"LabelPass": "Password",
"LabelRepeatPass": "Repeat Password",
"ButtonSubmit": "Login"
},
"EnterPass": {
"Heading": "Login",
"Description": "Please enter your password.",
"LabelPass": "Password",
"ButtonRecover": "Recover Password",
"LabelRememberance": "Remember me",
"ButtonSubmit": "Enter Menu"
},
"Errors": {
"PasswordLength": "Password must be at least 6 characters long",
"PasswordMatch": "Repeated password does not match",
"PhoneNumberFormat": "Phone number format is incorrect",
"OTPFormat": "Activation code is incomplete"
}
}
+39
View File
@@ -0,0 +1,39 @@
{
"Enter": {
"Heading": "ورود به سیستم",
"Description": "برای ورود شماره همراه خود را وارد نمایید.",
"LabelPhoneNumber": "شماره همراه",
"ButtonSubmit": "بعدی"
},
"OTP": {
"Heading": "کد فعالسازی را وارد کنید",
"Description": "کد ۶ رقمی ارسال شده به شماره {phoneNumber} را وارد نمایید.",
"Label": "",
"TimerRunning": "{seconds} ثانیه دیگر تا دریافت کد",
"TimerOut": "کد را دریافت نکردید؟",
"TimerReset": "دوباره امتحان کنید",
"ButtonSubmit": "بعدی"
},
"NewPassword": {
"HeadingCreatePass": "انتخاب کلمه عبور",
"HeadingResetPass": "تغییر کلمه عبور",
"Description": "کلمه عبور جدید باید ترکیبی از حروف بزرگ و کوچک و نشانه ها باشد مثل A126bdz@",
"LabelPass": "کلمه عبور",
"LabelRepeatPass": "تکرار کلمه عبور",
"ButtonSubmit": "ورود"
},
"EnterPass": {
"Heading": "ورود به سیستم",
"Description": "کلمه عبور خود را وارد نمایید.",
"LabelPass": "کلمه عبور",
"ButtonRecover": "بازیابی کلمه عبور",
"LabelRememberance": "مرا به خاطر بسپار",
"ButtonSubmit": "ورود به منو"
},
"Errors": {
"PasswordLength": "کلمه عبور باید شامل حداقل 6 کاراکتر باشد",
"PasswordMatch": "تکرار کلمه عبور مطابقت ندارد",
"PhoneNumberFormat": "فرمت شماره تلفن اشتباه است",
"OTPFormat": "کد فعالسازی کامل نیست"
}
}
+12
View File
@@ -0,0 +1,12 @@
import { i18nRouter } from 'next-i18n-router';
import { NextRequest } from 'next/server';
import i18nConfig from '../i18nConfig';
export function middleware(request: NextRequest) {
return i18nRouter(request, i18nConfig);
}
// only applies this middleware to files in the app directory
export const config = {
matcher: '/((?!api|static|favicon.ico|.*\\..*|_next).*)'
};