File size: 1,916 Bytes
c30ea2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { useLocale } from "@/i18n/compat/client";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { Languages } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { locales, localeNames } from "@/i18n/config";
import { getLocaleFromPathname, replacePathLocale } from "@/i18n/runtime";

export default function LanguageSwitch() {
  const locale = useLocale();
  const navigate = useNavigate();
  const pathname = useLocation({
    select: (location) => location.pathname
  });

  const handleSwitchLocale = (nextLocale: (typeof locales)[number]) => {
    document.cookie = `NEXT_LOCALE=${nextLocale}; path=/; max-age=31536000`;

    const currentPathLocale = getLocaleFromPathname(pathname);
    if (currentPathLocale) {
      navigate({ to: replacePathLocale(pathname, nextLocale) });
    }
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 relative hover:bg-accent/50"
        >
          <Languages className="h-[1.2rem] w-[1.2rem]" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        {locales.map((loc) => {
          return (
            <DropdownMenuItem
              key={loc}
              className={locale === loc ? "bg-accent" : ""}
              onClick={() => handleSwitchLocale(loc)}
            >
              <span className="flex items-center gap-2">
                {localeNames[loc]}
                {locale === loc && (
                  <span className="text-xs text-muted-foreground"></span>
                )}
              </span>
            </DropdownMenuItem>
          );
        })}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}