aboutsummaryrefslogtreecommitdiff
path: root/src/router.ts
blob: bcdf8ebbbeed89c03af44178c988324fa9730443 (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import * as Config from 'config'

export type Route
  = { name: 'form', config: Config.Config }
  | { name: 'timer', config: Config.Config }

export function from(location: Location): Route {
  const hash = location.hash.slice(1)
  const parts = hash.split('?')
  const path = parts[0]
  const search = parts.length > 1 ? parts[1] : ''

  const name = path.startsWith('/timer') ? 'timer' : 'form'
  let config = Config.init()
  if (search.length > 0) {
    search.split('&').forEach(entry => {
      const xs = entry.split('=')
      if (xs.length === 2) {
        const key = xs[0]
        if (key == 'warmup') config.warmup = parseInt(xs[1])
        else if (key == 'tabatas') config.tabatas = decodeTabatas(xs[1])
        else if (key == 'prepare') config.prepare = parseInt(xs[1])
        else if (key == 'cycles') config.cycles = parseInt(xs[1])
        else if (key == 'work') config.work = parseInt(xs[1])
        else if (key == 'rest') config.rest = parseInt(xs[1])
      }
    })
    const params = search.split('&')
  }

  return { name, config }
}

export function toString(route: Route): string {
  const path = route.name === 'form' ? '/' : '/timer'
  let query = ''
  if (route.config !== undefined) {
    const { warmup, tabatas, prepare, cycles, work, rest } = route.config
    const params = [
      `warmup=${warmup}`,
      `prepare=${prepare}`,
      `cycles=${cycles}`,
      `work=${work}`,
      `rest=${rest}`,
    ]
    if(tabatas.length > 0) {
      params.push(`tabatas=${encodeTabatas(tabatas)}`)
    }
    query = `?${params.join('&')}`
  }
  return `#${path}${query}`
}

function encodeTabatas(xs: string[]): string {
  return encodeURIComponent(xs.join(','))
}

function decodeTabatas(str: string): string[] {
  return decodeURIComponent(str).split(',').map(t => t.trim())
}