Use Jester's pattern matcher for simple routing.

This commit is contained in:
Dominik Picheta 2018-05-10 18:21:12 +01:00
commit 4176bdee3c
3 changed files with 29 additions and 10 deletions

View file

@ -1046,8 +1046,8 @@ proc selectThread(threadRow: seq[string]): Thread =
views: threadRow[2].parseInt,
activity: threadRow[3].parseInt,
creation: posts[1].parseInt,
isLocked: false,
isSolved: false # TODO: ^ and this. Add a field to `post` to identify.
isLocked: false, # TODO:
isSolved: false # TODO: Add a field to `post` to identify the solution.
)
# Gather the users list.

View file

@ -1,8 +1,8 @@
import strformat, times, options, json
import strformat, times, options, json, tables, future
from dom import window, Location
include karax/prelude
import jester/patterns
import threadlist, postlist, karaxutils
@ -40,13 +40,32 @@ proc genHeader(): VNode =
italic(class="fas fa-sign-in-alt")
text " Log in"
const appName = "/karax"
type Params = Table[string, string]
type
Route = object
n: string
p: proc (params: Params): VNode
proc r(n: string, p: proc (params: Params): VNode): Route = Route(n: n, p: p)
proc route(routes: openarray[Route]): VNode =
for route in routes:
let pattern = (appName & route.n).parsePattern()
let (matched, params) = pattern.match($state.url.pathname)
if matched:
return route.p(params)
proc render(): VNode =
result = buildHtml(tdiv()):
genHeader()
if "/t/" in state.url.pathname:
renderPostList(3806, false)
else:
renderThreadList()
route([
r("/t/@id?",
(params: Params) =>
(kout(params["id"].cstring);
renderPostList(params["id"].parseInt(), false))
),
r("/", (params: Params) => renderThreadList())
])
window.onPopState = onPopState
setRenderer render

View file

@ -56,7 +56,7 @@ when defined(js):
let parsed = parseJson($response)
let list = to(parsed, PostList)
if state.list.isSome:
if state.list.isSome and state.list.get().thread.id == list.thread.id:
state.list.get().posts.add(list.posts)
# TODO: Incorporate other possible changes?
else:
@ -101,7 +101,7 @@ when defined(js):
if state.status != Http200:
return renderError("Couldn't retrieve posts.")
if state.list.isNone:
if state.list.isNone or state.list.get().thread.id != threadId:
ajaxGet(makeUri("posts.json?id=" & $threadId), @[], onPostList)
return buildHtml(tdiv(class="loading loading-lg"))