Files
sass-mohfarawati/components/layout/locale-toggle.tsx
T

86 lines
3.0 KiB
TypeScript

"use client";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { AppLocale, getLocalizedPath, stripLocalePrefix } from "@/lib/locale";
import { cn } from "@/lib/utils";
type LocaleToggleProps = {
locale: string;
className?: string;
showLabel?: boolean;
};
export function LocaleToggle({ locale, className, showLabel = false }: LocaleToggleProps) {
const pathname = usePathname();
const locales: AppLocale[] = ["de", "en", "ar"];
const currentPath = stripLocalePrefix(pathname);
const currentLocale = (["de", "en", "ar"].includes(locale) ? locale : "de") as AppLocale;
const availableLocales = locales.filter((targetLocale) => targetLocale !== currentLocale);
const contentFontClassName = currentLocale === "ar" ? "font-arabic" : "font-latin";
const localeFlags: Record<AppLocale, { src: string; alt: string }> = {
de: { src: "/flags/de.svg", alt: "German" },
en: { src: "/flags/us.svg", alt: "English" },
ar: { src: "/flags/sy.svg", alt: "Arabic" },
};
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size={showLabel ? "sm" : "icon"}
aria-label={`Locale: ${currentLocale.toUpperCase()}`}
className={cn(
"group cursor-pointer rounded-pill border border-transparent text-muted-foreground hover:border-border/70 hover:bg-background/80 hover:text-foreground",
showLabel ? "gap-2 px-3" : undefined,
className,
)}
>
<Image
src={localeFlags[currentLocale].src}
alt={localeFlags[currentLocale].alt}
width={18}
height={18}
className="h-[18px] w-[18px] rounded-full object-cover transition-transform duration-300 ease-out group-hover:scale-110"
/>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className={cn("w-auto min-w-0", contentFontClassName)}>
{availableLocales.map((targetLocale) => (
<DropdownMenuItem
key={targetLocale}
asChild
className={cn(
"cursor-pointer",
targetLocale === "ar" ? "font-arabic" : "font-latin",
)}
>
<a
href={getLocalizedPath(targetLocale, currentPath)}
className="group flex items-center justify-center"
>
<Image
src={localeFlags[targetLocale].src}
alt={localeFlags[targetLocale].alt}
width={18}
height={18}
className="h-[18px] w-[18px] rounded-full object-cover transition-transform duration-300 ease-out group-hover:scale-110"
/>
</a>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}