File size: 912 Bytes
2471af3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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}`
|