diff --git a/src/components/BackButton/index.tsx b/src/components/BackButton/index.tsx index 7e4be548..b8083936 100644 --- a/src/components/BackButton/index.tsx +++ b/src/components/BackButton/index.tsx @@ -1,27 +1,51 @@ import { Button } from "@/components/ui/button"; import type { ReactNode } from "react"; import { MdArrowBack } from "react-icons/md"; +import { useEffect } from "react"; + +const VISITED_PATHS_KEY = "visited-paths"; +const MAX_VISITED_PATHS = 10; export const BackButton = (props: { href: string; buttonLabel?: ReactNode; contextLabel?: ReactNode; }) => { + useEffect(() => { + const currentPath = window.location.pathname; + const storedPaths = sessionStorage.getItem(VISITED_PATHS_KEY); + let visitedPaths = storedPaths ? JSON.parse(storedPaths) : []; + + if (!visitedPaths.includes(currentPath)) { + visitedPaths.push(currentPath); + + if (visitedPaths.length > MAX_VISITED_PATHS) { + visitedPaths = visitedPaths.slice(-MAX_VISITED_PATHS); + } + + sessionStorage.setItem(VISITED_PATHS_KEY, JSON.stringify(visitedPaths)); + } + }, []); + + const handleClick = (e: React.MouseEvent) => { + const referrer = document.referrer; + const hasReferrer = !!referrer && referrer.includes(window.location.host); + const hasHistory = window.history.length > 1; + + const storedPaths = sessionStorage.getItem(VISITED_PATHS_KEY); + const visitedPaths = storedPaths ? JSON.parse(storedPaths) : []; + const hasVisitedPaths = visitedPaths.length > 1; + + if (hasHistory && (hasReferrer || hasVisitedPaths)) { + e.preventDefault(); + window.history.back(); + } + }; + return (
diff --git a/src/layouts/RootLayout.astro b/src/layouts/RootLayout.astro index a11b1566..a1142995 100644 --- a/src/layouts/RootLayout.astro +++ b/src/layouts/RootLayout.astro @@ -1,4 +1,5 @@ --- +import { ClientRouter } from "astro:transitions"; import Analytics from "@vercel/analytics/astro"; import "@fontsource/tomorrow/400.css"; import "@fontsource/tomorrow/500.css"; @@ -30,8 +31,23 @@ import { Toaster } from "@/components/ui/sonner"; /> + + +