07f791d
ZhenYi
refactor: replace Preact with React imports for improved consistency across components
07f791d
import { useEffect, useState } from 'react'
export function navigationHref(path: string): string {
const target = new URL(path, location.href)
if (target.origin !== location.origin) return target.href
const current = new URLSearchParams(location.search)
for (const key of new Set(current.keys())) {
if (key === 'token' || target.searchParams.has(key)) continue
for (const value of current.getAll(key)) target.searchParams.append(key, value)
}
return `${target.pathname}${target.search}${target.hash}`
}
export function navigate(path: string, replace = false) {
const href = navigationHref(path)
const target = new URL(href, location.href)
if (target.origin !== location.origin) {
location.assign(href)
return
}
const sameDocument = target.pathname === location.pathname && target.search === location.search
if (replace) history.replaceState(null, '', href)
else history.pushState(null, '', href)
window.dispatchEvent(new PopStateEvent('popstate'))
if (target.hash) {
const anchor = document.getElementById(decodeURIComponent(target.hash.slice(1)))
if (anchor) {
anchor.scrollIntoView({ block: 'start' })
return
}
if (sameDocument) return
}
window.scrollTo(0, 0)
}
export function usePath() {
const [url, setUrl] = useState(location.pathname + location.search)
useEffect(() => {
const update = () => setUrl(location.pathname + location.search)
window.addEventListener('popstate', update)
return () => window.removeEventListener('popstate', update)
}, [])
return url.split('?')[0].replace(/\/$/, '') || '/'
}