File size: 1,100 Bytes
2471af3
ebe5562
2471af3
 
 
 
ebe5562
 
2471af3
 
 
ebe5562
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebe5562
2471af3
ebe5562
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
30
31
32
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])