app-template/app/web/src/lib/nav.ts

30 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { navigate } from "astro:transitions/client";
import "@/lib/history-guard";
/** 站内软导航(ClientRouter),避免整页 GET。 */
export function go(href: string): void {
void navigate(href);
}
/** 读取当前 URL 查询参数(浏览器侧)。 */
export function queryParam(name: string): string | null {
if (typeof window === "undefined") return null;
return new URLSearchParams(window.location.search).get(name);
}
/**
* 更新查询参数(不刷新,便于刷新/分享后停留在同一选集)。
* history-guard 会保证 replaceState 不把 ClientRouter 的 state 抹成 null,
* 否则 onPopState 直接 return,浏览器前进/后退只变地址栏、不换页。
*/
export function setQueryParams(params: Record<string, string | null>): void {
if (typeof window === "undefined") return;
const url = new URL(window.location.href);
for (const [key, value] of Object.entries(params)) {
if (value == null) url.searchParams.delete(key);
else url.searchParams.set(key, value);
}
if (url.toString() === window.location.href) return;
window.history.replaceState(window.history.state, "", url.toString());
}