"use client"; /** 记录当前浏览器条目的站内来源;返回优先沿真实历史,直接打开深链时回父页面。 */ import type { Route } from "next"; import { useEffect, useRef } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { safeDigitalReturnTo } from "@/lib/digital-routes"; /** 共享布局持续存在,让不同路由的进入顺序成为浏览器真实历史。 */ export function DigitalRouteHistory() { const pathname = usePathname(); const searchParams = useSearchParams(); const previous = useRef(null); useEffect(() => { const path = window.location.pathname + window.location.search + window.location.hash; const state = window.history.state ?? {}; // 后退恢复的是已有条目,不能把它的来源覆盖成刚离开的页面。 if (state.stellarNavigation?.path !== path) { const existing = state.stellarNavigation; // 筛选只替换当前 URL,不凭空增加一次返回步骤。 const samePage = typeof existing?.path === "string" && new URL(existing.path, window.location.origin).pathname === pathname; window.history.replaceState( { ...state, stellarNavigation: { path, previous: samePage ? existing.previous : previous.current, }, }, "", path, ); } previous.current = path; }, [pathname, searchParams]); return null; } /** 页面内返回按钮与浏览器后退一致;外部打开或新标签页不返回站外。 */ export function useDigitalBack(fallback: Route) { const router = useRouter(); return () => { const previous = window.history.state?.stellarNavigation?.previous; if ( typeof previous === "string" && safeDigitalReturnTo(previous) === previous ) router.back(); else router.replace(fallback); }; }