No description
Find a file
2025-05-31 15:04:41 -03:00
.github ci 2025-05-29 12:54:05 -03:00
.gitignore gitignore 2025-05-29 12:50:08 -03:00
kxrouter.nim Allow onNextTick within onNextTick 2025-05-31 15:02:08 -03:00
kxrouter.nimble bump 2025-05-31 15:04:41 -03:00
LICENSE init 2025-05-29 12:47:17 -03:00
README.md readme 2025-05-29 20:31:44 -03:00

KxRouter

KxRouter is a karax router with life-time events.

Usage

include pkg/karax/prelude
import pkg/kxrouter

proc notFoundView(ctx: ViewContext): VNode =
  buildHtml text("Not found")

proc home(ctx: ViewContext): VNode =
  buildHtml text("Hello world!")

proc events(ctx: ViewContext): VNode =
  ctx.onLoad proc (ctx: ViewContext) = echo "Loaded"
  ctx.onUnload proc (ctx: ViewContext) = echo "Unloaded"
  ctx.onMount proc (ctx: ViewContext) = echo "Mounted"
  ctx.onNextTick proc (ctx: ViewContext) = echo "Next Tick"
  buildHtml text("Events")

proc params(ctx: ViewContext): VNode =
  let foo = ctx.params.getOrDefault "foo"
  buildHtml text(foo)

kxRouter(@[
  ("#/home", home),
  ("#/events", events),
  ("#/params/{foo}", params)
], notFoundView)

Events

The events run for the given view. There are no global events. The received ctx callback parameter is always the one used to register the callback.

  • Use onLoad for initialization. This runs when the route/view is visited.
  • Use onUnload for cleaning up. This runs when the route/view is exited.
  • Use onMount to run in the next post-render after visiting the route/view.
  • Use onNextTick to run in the next post-render. Useful for changing some DOM element after fetching resources, for example scrolling down the element.

ajaxGet/fetch

When fetching resources, the "done" callback may run after the user has navigated to a different route. Use if ctx.isUnloaded: return to return early and avoid undesired side-effects.

include pkg/karax/prelude
import pkg/karax/kajax
import pkg/kxrouter

var books = newSeq[string]()

proc loadBooks(ctx: ViewContext) {.raises: [].} =
  books.setLen 0
  ajaxGet("/book/list", @[], proc (status: int, response: cstring) =
    if ctx.isUnloaded:
      return
    if status == 200:
      let data = parse response
      for book in data["books"]:
        books.add book.getStr()
    else:
      console.log "err"

proc shelf(ctx: ViewContext): VNode =
  ctx.onLoad loadBooks
  buildHtml tdiv(class="books"):
    for book in books:
      tdiv(class="book"):
        text book

SSR

Server side rendering:

import pkg/karax/[karaxdsl, vdom]
import pkg/kxrouter

proc notFoundView(ctx: ViewContext): VNode =
  buildHtml text("Not found")

proc books(ctx: ViewContext): VNode =
  buildHtml text("books")

let router = router(@[("#/books", books)], notFoundView)
doAssert "books" in $router("#/books", "book=foo&page=1")

These life-time events are ignored in SSR: onMount and onNextTick.

LICENSE

MIT