From 4176bdee3cd199e0bec1f2146f6a5183cc7dbc4a Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 10 May 2018 18:21:12 +0100 Subject: [PATCH] Use Jester's pattern matcher for simple routing. --- forum.nim | 4 ++-- redesign/forum.nim | 31 +++++++++++++++++++++++++------ redesign/postlist.nim | 4 ++-- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/forum.nim b/forum.nim index ef97f85..025e109 100644 --- a/forum.nim +++ b/forum.nim @@ -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. diff --git a/redesign/forum.nim b/redesign/forum.nim index 8aaa425..efa4780 100644 --- a/redesign/forum.nim +++ b/redesign/forum.nim @@ -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 \ No newline at end of file diff --git a/redesign/postlist.nim b/redesign/postlist.nim index 33ed677..52978bf 100644 --- a/redesign/postlist.nim +++ b/redesign/postlist.nim @@ -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"))