saladday1's picture
code: sync from git
ebe5562 verified
Raw History Blame Contribute Delete
1.1 kB
import { useEffect, useState } from "react"
import { getLang, hashFor, splitHash } from "@/lib/i18n"
/** 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
* each with an optional language suffix first: #/ch, #/ch/language/m2.7, #/en/... (lib/i18n). */
export type Route = { cat: string | null; rel: string | null }
const parse = (): Route => {
const [cat, rel] = splitHash().rest.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
}
/** A link within the page, in the language on screen. */
export const href = (cat?: string | null, rel?: string | null) =>
hashFor(getLang(), !cat ? [] : rel ? [cat, encodeURIComponent(rel)] : [cat])