feat(website): add next-intl i18n and dark mode support

This commit is contained in:
justsisyphus
2026-01-24 05:20:20 +09:00
parent b7d3417d2e
commit f28c8a45dd
19 changed files with 392 additions and 57 deletions
+58
View File
@@ -0,0 +1,58 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "../globals.css";
import { ThemeProvider } from "@/components/theme-provider";
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { notFound } from 'next/navigation';
import { routing } from '@/i18n/routing';
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default async function RootLayout({
children,
params
}: {
children: React.ReactNode;
params: Promise<{ locale: string }>;
}) {
const { locale } = await params;
if (!routing.locales.includes(locale as any)) {
notFound();
}
const messages = await getMessages();
return (
<html lang={locale} suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<NextIntlClientProvider messages={messages}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</NextIntlClientProvider>
</body>
</html>
);
}
@@ -1,8 +1,17 @@
import Image from "next/image";
import { ThemeToggle } from "@/components/theme-toggle";
import LanguageSwitcher from "@/components/LanguageSwitcher";
import { useTranslations } from "next-intl";
export default function Home() {
const t = useTranslations("Common");
return (
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black relative">
<div className="absolute top-4 right-4 flex gap-2">
<LanguageSwitcher />
<ThemeToggle />
</div>
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
@@ -14,24 +23,10 @@ export default function Home() {
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
{t("title")}
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
{t("description")}
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
@@ -48,7 +43,7 @@ export default function Home() {
width={16}
height={16}
/>
Deploy Now
{t("getStarted")}
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
@@ -56,7 +51,7 @@ export default function Home() {
target="_blank"
rel="noopener noreferrer"
>
Documentation
{t("learnMore")}
</a>
</div>
</main>
-34
View File
@@ -1,34 +0,0 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}
@@ -0,0 +1,37 @@
"use client";
import { useLocale, useTranslations } from "next-intl";
import { usePathname, useRouter } from "@/i18n/routing";
import { ChangeEvent, useTransition } from "react";
export default function LanguageSwitcher() {
const t = useTranslations("LanguageSwitcher");
const locale = useLocale();
const router = useRouter();
const pathname = usePathname();
const [isPending, startTransition] = useTransition();
function onSelectChange(event: ChangeEvent<HTMLSelectElement>) {
const nextLocale = event.target.value;
startTransition(() => {
router.replace(pathname, { locale: nextLocale });
});
}
return (
<label className="border-2 rounded">
<p className="sr-only">{t("label")}</p>
<select
defaultValue={locale}
className="bg-transparent py-2"
onChange={onSelectChange}
disabled={isPending}
>
<option value="en">English</option>
<option value="ko"></option>
<option value="zh"></option>
<option value="ja"></option>
</select>
</label>
);
}
@@ -0,0 +1,50 @@
// @vitest-environment jsdom
import { render, screen, fireEvent } from "@testing-library/react";
import { ThemeToggle } from "../theme-toggle";
import { describe, it, expect, vi } from "vitest";
import * as nextThemes from "next-themes";
// Mock next-themes
vi.mock("next-themes", async () => {
const actual = await vi.importActual("next-themes");
return {
...actual,
useTheme: vi.fn(),
};
});
describe("ThemeToggle", () => {
it("calls setTheme to dark when current theme is light", () => {
// given
const setThemeMock = vi.fn();
(nextThemes.useTheme as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
theme: "light",
setTheme: setThemeMock,
});
// when
render(<ThemeToggle />);
const button = screen.getByRole("button", { name: /toggle theme/i });
fireEvent.click(button);
// then
expect(setThemeMock).toHaveBeenCalledWith("dark");
});
it("calls setTheme to light when current theme is dark", () => {
// given
const setThemeMock = vi.fn();
(nextThemes.useTheme as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
theme: "dark",
setTheme: setThemeMock,
});
// when
render(<ThemeToggle />);
const button = screen.getByRole("button", { name: /toggle theme/i });
fireEvent.click(button);
// then
expect(setThemeMock).toHaveBeenCalledWith("light");
});
});
+11
View File
@@ -0,0 +1,11 @@
"use client";
import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}
+39
View File
@@ -0,0 +1,39 @@
"use client";
import * as React from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
export function ThemeToggle() {
const { setTheme, theme } = useTheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return (
<button
type="button"
className="relative rounded-md p-2 hover:bg-accent hover:text-accent-foreground"
disabled
>
<Sun className="h-[1.2rem] w-[1.2rem] opacity-0" />
<span className="sr-only">Toggle theme</span>
</button>
);
}
return (
<button
type="button"
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
className="relative rounded-md p-2 hover:bg-accent hover:text-accent-foreground"
>
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute top-2 left-2 h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</button>
);
}
+6
View File
@@ -0,0 +1,6 @@
import { defineRouting } from 'next-intl/routing';
export const routing = defineRouting({
locales: ['en', 'ko', 'zh', 'ja'],
defaultLocale: 'en'
});
+15
View File
@@ -0,0 +1,15 @@
import { getRequestConfig } from 'next-intl/server';
import { routing } from './config';
export default getRequestConfig(async ({ requestLocale }) => {
let locale = await requestLocale;
if (!locale || !routing.locales.includes(locale as any)) {
locale = routing.defaultLocale;
}
return {
locale,
messages: (await import(`../../messages/${locale}.json`)).default
};
});
+12
View File
@@ -0,0 +1,12 @@
import { describe, it, expect } from 'vitest';
import { routing } from './config';
describe('i18n routing', () => {
it('should have correct locales', () => {
expect(routing.locales).toEqual(['en', 'ko', 'zh', 'ja']);
});
it('should have correct default locale', () => {
expect(routing.defaultLocale).toBe('en');
});
});
+7
View File
@@ -0,0 +1,7 @@
import { createNavigation } from 'next-intl/navigation';
import { routing } from './config';
export { routing };
export const { Link, redirect, usePathname, useRouter, getPathname } =
createNavigation(routing);
+8
View File
@@ -0,0 +1,8 @@
import createMiddleware from 'next-intl/middleware';
import { routing } from './i18n/config';
export default createMiddleware(routing);
export const config = {
matcher: ['/', '/(ko|en|zh|ja)/:path*']
};