R/router.R

Defines functions routerUI routerModule route

#' @importFrom shinyHistory useShinyHistory history
#' @export
NULL

#' @export
routerUI <- function(id) {
  ns <- shiny::NS(id)
  shiny::tagList(
    shiny::uiOutput(ns("ui"))
  )
}

#' @export
routerModule <- function(input, output, session, ..., history) {
  ns <- session$ns
  router <- list()
  router$params <- shiny::reactiveVal(list())

  routes <- list(...)

  output$ui <- shiny::renderUI({
    path <- history$location$pathname
    if (is.null(path)) return(NULL)

    for (route in routes) {
      if ((match <- regexpr(route$path, path, perl = TRUE)) == -1) next

      start <- attr(match, "capture.start")[1, ]
      length <- attr(match, "capture.length")[1, ]
      if (!is.null(start) && !is.null(length)) {
        params <- as.list(substring(path, start, start + length - 1))
        names(params) <- attr(match, "capture.names")
        router$params(params)
      }

      return(route$ui)
    }
  })

  router
}


#' @export
route <- function(path, ui) {
  list(path = path, ui = ui)
}
shunsambongi/shinyRouter documentation built on Nov. 5, 2019, 8:54 a.m.