"use client"; import getEnv from "@/lib/env-entry"; import { cn } from "@/lib/utils"; import { m } from "framer-motion"; import { useTranslations } from "next-intl"; import React, { createRef, useEffect, useRef } from "react"; export default function Switch({ allTag, nowTag, tagCountMap, onTagChange, }: { allTag: string[]; nowTag: string; tagCountMap: Record; onTagChange: (tag: string) => void; }) { const scrollRef = useRef(null); const tagRefs = useRef(allTag.map(() => createRef())); const t = useTranslations("ServerListClient"); useEffect(() => { const savedTag = sessionStorage.getItem("selectedTag"); if (savedTag && allTag.includes(savedTag)) { onTagChange(savedTag); } }, [allTag, onTagChange]); useEffect(() => { const container = scrollRef.current; if (!container) return; const isOverflowing = container.scrollWidth > container.clientWidth; if (!isOverflowing) return; const onWheel = (e: WheelEvent) => { e.preventDefault(); container.scrollLeft += e.deltaY; }; container.addEventListener("wheel", onWheel, { passive: false }); return () => { container.removeEventListener("wheel", onWheel); }; }, []); useEffect(() => { const currentTagRef = tagRefs.current[allTag.indexOf(nowTag)]; if (currentTagRef && currentTagRef.current) { currentTagRef.current.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center", }); } }, [nowTag]); return (
{allTag.map((tag, index) => (
onTagChange(tag)} className={cn( "relative cursor-pointer rounded-3xl px-2.5 py-[8px] text-[13px] font-[600] transition-all duration-500", nowTag === tag ? "text-black dark:text-white" : "text-stone-400 dark:text-stone-500", )} > {nowTag === tag && ( )}
{tag === "defaultTag" ? t("defaultTag") : tag}{" "} {getEnv("NEXT_PUBLIC_ShowTagCount") === "true" && tag !== "defaultTag" && (
{tagCountMap[tag]}
)}
))}
); }