"use client"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { cn } from "@suphark/ui/lib/utils"; import { useRouter } from "next/navigation"; import { useEffect, useTransition } from "react"; import { toast } from "sonner"; interface TransitionLinkProps extends React.AnchorHTMLAttributes { href: string; children?: React.ReactNode; } /** * A client-side link that uses useTransition to show pending UI (Toast, opacity) * without blocking the UI, providing a smoother navigation experience * than a standard Next.js or router.push(). */ export function TransitionLink({ href, children, className, onClick, ...props }: TransitionLinkProps) { const router = useRouter(); const [isPending, startTransition] = useTransition(); const loadingText = useUiText().navigating ?? "กำลังโหลด..."; // Handle Toast notification for loading state useEffect(() => { if (isPending) { // Use a fixed ID to prevent toast stacking on rapid clicks const toastId = "page-transition-loading"; toast.loading(loadingText, { id: toastId }); // Clean up: Dismiss toast when transition finishes (isPending -> false) // or when the component unmounts (navigation completes) return () => { toast.dismiss(toastId); }; } }, [isPending, loadingText]); const handleClick = (e: React.MouseEvent) => { if (onClick) { onClick(e); } if (e.defaultPrevented) return; // Ctrl/⌘/Shift+click หรือคลิกกลาง = ผู้ใช้ต้องการเปิดแท็บ/หน้าต่างใหม่ → ปล่อยให้ browser จัดการ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return; e.preventDefault(); startTransition(() => { router.push(href); }); }; return ( {children} ); }