|
1 | 1 | import { Button } from "@/components/ui/button"; |
2 | 2 | import type { ReactNode } from "react"; |
3 | 3 | import { MdArrowBack } from "react-icons/md"; |
4 | | -import { useEffect, useState } from "react"; |
| 4 | +import { useEffect } from "react"; |
| 5 | + |
| 6 | +const VISITED_PATHS_KEY = "visited-paths"; |
5 | 7 |
|
6 | 8 | export const BackButton = (props: { |
7 | 9 | href: string; |
8 | 10 | buttonLabel?: ReactNode; |
9 | 11 | contextLabel?: ReactNode; |
10 | 12 | }) => { |
11 | | - const [canGoBack, setCanGoBack] = useState(false); |
12 | | - |
13 | 13 | useEffect(() => { |
14 | | - const checkBackNavigation = () => { |
15 | | - setCanGoBack(window.history.length > 1); |
16 | | - }; |
17 | | - |
18 | | - checkBackNavigation(); |
19 | | - document.addEventListener("astro:page-load", checkBackNavigation); |
| 14 | + const currentPath = window.location.pathname; |
| 15 | + const storedPaths = sessionStorage.getItem(VISITED_PATHS_KEY); |
| 16 | + const visitedPaths = storedPaths ? JSON.parse(storedPaths) : []; |
20 | 17 |
|
21 | | - return () => { |
22 | | - document.removeEventListener("astro:page-load", checkBackNavigation); |
23 | | - }; |
| 18 | + if (!visitedPaths.includes(currentPath)) { |
| 19 | + visitedPaths.push(currentPath); |
| 20 | + sessionStorage.setItem(VISITED_PATHS_KEY, JSON.stringify(visitedPaths)); |
| 21 | + } |
24 | 22 | }, []); |
25 | 23 |
|
26 | 24 | const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => { |
27 | | - if (canGoBack) { |
| 25 | + const referrer = document.referrer; |
| 26 | + const hasReferrer = !!referrer && referrer.includes(window.location.host); |
| 27 | + const hasHistory = window.history.length > 1; |
| 28 | + |
| 29 | + const storedPaths = sessionStorage.getItem(VISITED_PATHS_KEY); |
| 30 | + const visitedPaths = storedPaths ? JSON.parse(storedPaths) : []; |
| 31 | + const hasVisitedPaths = visitedPaths.length > 1; |
| 32 | + |
| 33 | + if (hasHistory && (hasReferrer || hasVisitedPaths)) { |
28 | 34 | e.preventDefault(); |
29 | 35 | window.history.back(); |
30 | 36 | } |
|
0 commit comments