This commit is contained in:
1 parent
c1541b80df
commit
b4c7908029
97 files changed
+12403
-154
No files matched your search
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { usePathname, useRouter } from "@/i18n/navigation";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { Globe } from "lucide-react";
|
||||
import { routing } from "@/i18n/routing";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* 语言切换器。
|
||||
*
|
||||
* 使用 next-intl 的 usePathname / useRouter,切换语言时保留当前路径,
|
||||
* 而不是跳回首页。通过 useParams 需要传参的场景在这里不适用,
|
||||
* 因为本项目的动态段只有 slug,路径本身已经能表达。
|
||||
*/
|
||||
export function LocaleSwitcher({ className }: { className?: string }) {
|
||||
const t = useTranslations("LocaleSwitcher");
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const handleSelect = (nextLocale: string) => {
|
||||
setOpen(false);
|
||||
router.replace(pathname, { locale: nextLocale });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-label={t("label")}
|
||||
className="inline-flex h-9 items-center gap-[6px] rounded-full px-sm text-body-sm text-steel transition-colors duration-150 active:bg-surface"
|
||||
>
|
||||
<Globe className="size-4" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t(locale)}</span>
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<>
|
||||
{/* 点击遮罩关闭菜单 */}
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
aria-hidden="true"
|
||||
onClick={() => setOpen(false)}
|
||||
className="fixed inset-0 z-40 cursor-default"
|
||||
/>
|
||||
|
||||
<ul
|
||||
role="listbox"
|
||||
aria-label={t("label")}
|
||||
className="absolute right-0 z-50 mt-xs min-w-[140px] overflow-hidden rounded-md border border-hairline bg-canvas py-xxs shadow-card"
|
||||
>
|
||||
{routing.locales.map((item) => (
|
||||
<li key={item}>
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={item === locale}
|
||||
onClick={() => handleSelect(item)}
|
||||
className={cn(
|
||||
"flex w-full items-center px-md py-xs text-left text-body-sm transition-colors duration-150",
|
||||
item === locale
|
||||
? "bg-surface font-medium text-ink"
|
||||
: "text-steel active:bg-surface",
|
||||
)}
|
||||
>
|
||||
{t(item)}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user