saladday1's picture
code: sync from git
2471af3 verified
Raw History Blame
912 Bytes
import { useEffect, useState } from "react"
/** Hash routes, because a static Space serves only index.html at the root:
* #/ the landing page
* #/language a category, its first release selected
* #/language/m2.7 */
export type Route = { cat: string | null; rel: string | null }
const parse = (): Route => {
const [cat, rel] = location.hash.replace(/^#\/?/, "").split("/").map((s) => decodeURIComponent(s))
return { cat: cat || null, rel: rel || null }
}
export function useRoute(): Route {
const [r, setR] = useState(parse)
useEffect(() => {
const on = () => {
setR(parse())
window.scrollTo({ top: 0 })
}
addEventListener("hashchange", on)
return () => removeEventListener("hashchange", on)
}, [])
return r
}
export const href = (cat?: string | null, rel?: string | null) =>
!cat ? "#/" : rel ? `#/${cat}/${encodeURIComponent(rel)}` : `#/${cat}`