Skip to content

Commit

Permalink
Merge pull request #35 from JosephGasiorekUSDS/jgasiorek-ffs-945
Browse files Browse the repository at this point in the history
FFS-945: i18n Chooser
  • Loading branch information
JosephGasiorekUSDS authored Jun 26, 2024
2 parents 405aef3 + 774b25b commit 4e4c979
Show file tree
Hide file tree
Showing 45 changed files with 232 additions and 53 deletions.
1 change: 0 additions & 1 deletion app/I18nTesting.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ async function getRes() {
}

const res = await getRes()
console.log(res)

await i18n
.use(initReactI18next)
Expand Down
17 changes: 17 additions & 0 deletions app/TranslationsProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use client'

import { I18nextProvider } from 'react-i18next'
import { initTranslations} from '@/app/i18n'
import { createInstance } from 'i18next'

interface TranslationsProviderProps {
children: React.ReactNode
locale: string
}

export default async function TranslationsProvider({ children, locale }: TranslationsProviderProps) {
const i18n = createInstance()
await initTranslations(locale, i18n)

return (<I18nextProvider i18n={i18n}>{children}</I18nextProvider>)
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
44 changes: 44 additions & 0 deletions app/[locale]/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import StoreProvider from '@/app/StoreProvider'
import "./globals.css";
import GovernmentBanner from "@/app/components/GovernmentBanner";
import InitialStateLoader from "@/app/InitialStateLoader";
import TranslationsProvider from "../TranslationsProvider";
import { i18nConfig } from "@/app/constants";
const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
title: "Verify.gov",
};

export function generateStaticParams() {
return i18nConfig.locales.map(locale => {
return {locale}
})
}

function RootLayout({
children,
params
}: Readonly<{
children: React.ReactNode
params: any
}>) {
return (
<html lang={params.locale}>
<body className={inter.className}>
<StoreProvider>
<InitialStateLoader>
<TranslationsProvider locale={params.locale}>
<GovernmentBanner />
{children}
</TranslationsProvider>
</InitialStateLoader>
</StoreProvider>
</body>
</html>
);
}

export default RootLayout
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
5 changes: 4 additions & 1 deletion app/page.test.tsx → app/[locale]/page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import mockRouter from 'next-router-mock'
describe('Intro Page', async () => {
let store: EnhancedStore
beforeEach(() => {
vi.mock('next/navigation', () => require('next-router-mock'))
vi.mock('next/navigation', () => ({
useRouter: () => mockRouter,
usePathname: () => mockRouter.asPath,
}))
mockRouter.push('/')
store = makeStore()
render (<Provider store={store}><Page /></Provider>)
Expand Down
16 changes: 6 additions & 10 deletions app/page.tsx → app/[locale]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import "@trussworks/react-uswds/lib/uswds.css"
import "@trussworks/react-uswds/lib/index.css"

import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
import { Grid, GridContainer, Header, Title, Icon, Button, Accordion, HeadingLevel } from "@trussworks/react-uswds";
import { useTranslation } from "react-i18next";
import { Grid, GridContainer, Icon, Button, Accordion, HeadingLevel } from "@trussworks/react-uswds";
import VerifyNav from "@/app/components/VerifyNav";

export default function Home() {
const { t } = useTranslation()
Expand All @@ -32,17 +33,12 @@ export default function Home() {
expanded: false,
id: 'intro_how_do_i_know',
headingLevel: 'h4' as HeadingLevel,
}]
}
]

return (
<div>
<Header basic={true}>
<div className="usa-nav-container">
<div className="usa-navbar">
<Title>{t('intro_title')}</Title>
</div>
</div>
</Header>
<VerifyNav title={t('intro_title')} />
<div className="usa-section">
<GridContainer>
<Grid row gap>
Expand Down
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
12 changes: 10 additions & 2 deletions app/api/sitemap/route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import { i18nConfig } from "@/app/constants";
import { readdir } from "fs/promises";
import { pathToFileURL } from "url";

export async function GET() {
export async function GET(req: Request) {
const files = await readdir(pathToFileURL('app'), { recursive: true })
const locs = files
.filter(file => file.endsWith('page.tsx'))
.map((file) => {
let name = file.substring(0, file.indexOf('page.tsx'))
return `<url><loc>http://localhost:3000/${name}</loc></url>`
if (name.indexOf('[locale]') === -1) {
return `<url><loc>http://${req.headers.get('host')}/${name}</loc></url>`
}

return i18nConfig.locales.map((locale) => {
const n = name.replace("[locale]", locale)
return `<url><loc>http://${req.headers.get('host')}/${n}</loc></url>`
}).join('\n')
})

const content = `<?xml version="1.0" encoding="UTF-8"?>
Expand Down
62 changes: 62 additions & 0 deletions app/components/VerifyNav.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { Header, Link, NavMenuButton, PrimaryNav, Title } from "@trussworks/react-uswds"
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { i18nConfig } from "@/app/constants"
import { usePathname, useRouter } from "next/navigation"
import { useCookies } from "react-cookie"

interface VerifyNavProps {
title: string
}

export default function VerifyNav(props: VerifyNavProps) {
const { t, i18n } = useTranslation()
const router = useRouter()
const currentPathname = usePathname()
const [cookies, setCookie] = useCookies([i18nConfig.cookieName]);
const currentLocale = i18n.language
const [expanded, setExpanded] = useState(false)

function changeLang(locale: string) {
i18n.changeLanguage(locale)
setCookie(i18nConfig.cookieName, locale)

if (locale === i18nConfig.defaultLocale) {
router.push(currentPathname.replace(`${currentLocale}`, ''));
} else if (currentLocale == i18nConfig.defaultLocale) {
router.push(`/${locale}/${currentPathname}`)
} else {
router.push(currentPathname.replace(`/${currentLocale}`, `/${locale}`) + "/")
}
router.refresh();
}

function makeNavItem(text: string, lang: string) {
const isCurrent = i18n.language?.startsWith(lang) ?? "en"
return <Link
href="#"
className={`usa-nav__link ${isCurrent ? "usa-current" : ""}`}
onClick={() => {changeLang(lang) }}
>{text}</Link>
}

const navItems = [
makeNavItem(t('nav_english'), "en"),
makeNavItem(t('nav_espanol'), "es"),
]

const onClick = () => {
setExpanded(prev => !prev)
}
return (
<Header basic={true} showMobileOverlay={expanded}>
<div className="usa-nav-container">
<div className="usa-navbar">
<Title>{props.title}</Title>
<NavMenuButton onClick={onClick} label="Menu" />
</div>
<PrimaryNav items={navItems} mobileExpanded={expanded} onToggleMobileNav={onClick} />
</div>
</Header>
)
}
6 changes: 6 additions & 0 deletions app/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

export const i18nConfig = {
locales: ['en', 'es'],
defaultLocale: 'en',
cookieName: 'NEXT_LOCALE',
}
26 changes: 15 additions & 11 deletions app/i18n.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import resourcesToBackend from 'i18next-resources-to-backend'
import { i18nConfig } from './constants';

i18n
.use(LanguageDetector)
.use(initReactI18next)
.use(resourcesToBackend((language, namespace) => import(`./i18n/locales/${language}/${namespace}.json`)))
.init({
debug: process.env.NODE_ENV !== "production" ,
fallbackLng: 'en'
});
export async function initTranslations(
locale,
i18nInstance
) {
i18nInstance = i18nInstance || createInstance()
i18nInstance.use(initReactI18next)
i18nInstance.use(resourcesToBackend((language, namespace) => import(`./i18n/locales/${language}/${namespace}.json`)))

export default i18n;
return i18nInstance.init({
debug: process.env.NODE_ENV !== "production" ,
lng: locale,
fallbackLng: i18nConfig.defaultLocale,
supportedLngs: i18nConfig.locales,
})
}
4 changes: 3 additions & 1 deletion app/i18n/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,5 +157,7 @@
"snap_recommend_deduction_take_body": "We recommend this!",
"snap_recommend_deduction_do_not_take_header": "Do not take the SNAP standard deduction, use my Medicaid expenses",
"snap_recommend_deduction_continue_button": "Continue",
"required_field_description": "A red asterisk (<0></0>) indicates a required field."
"required_field_description": "A red asterisk (<0></0>) indicates a required field.",
"nav_english": "English",
"nav_espanol": "Español"
}
23 changes: 23 additions & 0 deletions app/i18n/locales/es/translation.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"intro_title": "Verify.gov | Auto-empleo",
"intro_header": "Envíe prueba de sus ingresos por trabajo autónomo, por contrato independiente o por cuenta propia",
"intro_subheader": "Le ayudaremos a documentar sus ingresos como trabajador independiente o en efectivo y enviarlos a su solicitud de beneficios para que pueda obtener beneficios más rápido.",
"intro_secure": "Tu información está segura",
"intro_get_started_button": "Empezar",
"intro_how_do_i_know_header": "¿Cómo sé si soy autónomo?",
"intro_how_do_i_know_body_list_header": "Una persona puede trabajar por cuenta propia si:",
"intro_how_do_i_know_list_have_expenses": "Tienen gastos comerciales que nadie para quienes trabajan les paga.",
"intro_how_do_i_know_list_they_receive": "Reciben el formulario de impuestos 1099-MISC de una empresa o individuo al final del año.",
"intro_how_do_i_know_list_own": "Poseen o dirigen su propio negocio.",
"intro_how_do_i_know_list_benefits": "No reciben beneficios laborales ni contribuciones fiscales del individuo o empresa para la que trabajan.",
"nav_english": "English",
"nav_espanol": "Español",
"benefits_title": "Programas de beneficios",
"benefits_header": "¿Cuándo deben demostrarse los programas de beneficios en el libro mayor?",
"benefits_subheader_select": "Seleccione los beneficios de los que le gustaría ver una demostración.",
"benefits_medicaid": "Medicaid (atención médica)",
"benefits_snap": "SNAP (asistencia alimentaria)",
"benefits_continue_button": "Continuar",
"benefits_snap_hint": "Nota: Actualmente, el libro mayor asumirá que hay una deducción estándar del 50 % disponible para SNAP.",
"benefits_error_message": "Debes seleccionar al menos uno de los siguientes beneficios"
}
26 changes: 0 additions & 26 deletions app/layout.tsx

This file was deleted.

11 changes: 11 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { i18nRouter } from 'next-i18n-router';
import { i18nConfig } from './app/constants';
import { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
return i18nRouter(request, i18nConfig);
}

export const config = {
matcher: '/((?!api|static|.*\\..*|_next).*)'
};
29 changes: 29 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"lint": "next lint",
"test": "vitest",
"coverage": "vitest run --coverage",
"pa11y-ci": "pa11y-ci --sitemap http://localhost:3000/api/sitemap --config .pa11yci --sitemap-exclude localhost:3000/benefits"
"pa11y-ci": "pa11y-ci --sitemap http://localhost:3000/api/sitemap --config .pa11yci --sitemap-exclude /benefits"
},
"dependencies": {
"@reduxjs/toolkit": "^2.2.5",
Expand All @@ -18,6 +18,7 @@
"i18next-browser-languagedetector": "^8.0.0",
"i18next-resources-to-backend": "^1.2.1",
"next": "14.2.3",
"next-i18n-router": "^5.5.0",
"next-i18next": "^15.3.0",
"next-router-mock": "^0.9.13",
"react": "^18",
Expand Down

0 comments on commit 4e4c979

Please sign in to comment.