Files
Speisekarte/components/i18n/LanguageSwitcher.tsx
T
florian.wilde 33909c660b i18n-Fundament: Cookie-basierte Sprachumschaltung (DE/EN/PL)
Wörterbücher unter lib/i18n statt next-intl (Next.js 16 ist neu genug,
dass eine externe Routing-Middleware zusätzliches Risiko bedeutet
hätte); Sprache liegt in einem Cookie, kein URL-Präfix nötig, dadurch
bleibt proxy.ts unverändert. LocaleProvider stellt Wörterbuch + Sprache
per Context für Client-Komponenten bereit (lib/i18n/shared.ts ist
bewusst getrennt von lib/i18n/index.ts, damit next/headers nicht in
den Client-Bundle gelangt).
2026-07-18 02:08:01 +02:00

59 lines
1.6 KiB
TypeScript

"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { LOCALES, LOCALE_LABELS } from "@/lib/i18n/shared";
import type { Locale } from "@/lib/i18n/shared";
import { useLocale } from "@/components/i18n/LocaleProvider";
export default function LanguageSwitcher({
className = "",
variant = "dark",
}: {
className?: string;
variant?: "dark" | "light";
}) {
const locale = useLocale();
const router = useRouter();
const [busy, setBusy] = useState(false);
async function change(next: Locale) {
if (next === locale || busy) return;
setBusy(true);
await fetch("/api/locale", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ locale: next }),
});
router.refresh();
setBusy(false);
}
const activeCls =
variant === "dark" ? "bg-white/25 text-white" : "bg-gray-200 text-gray-900";
const inactiveCls =
variant === "dark"
? "text-white/60 hover:text-white hover:bg-white/10"
: "text-gray-400 hover:text-gray-700 hover:bg-gray-100";
return (
<div className={`flex gap-1 text-xs ${className}`} aria-label="Sprache">
{LOCALES.map((l) => (
<button
key={l}
type="button"
onClick={() => change(l)}
disabled={busy}
aria-current={l === locale}
title={LOCALE_LABELS[l]}
className={`rounded px-1.5 py-0.5 uppercase font-semibold transition-colors ${
l === locale ? activeCls : inactiveCls
}`}
>
{l}
</button>
))}
</div>
);
}