Search code examples
rshinystatic-files

How to add static files to shiny R package for new input control


I've try to use addResourcePath and include extdata directory (that's in inst directory):

to have script and css file in my custom input function:

#' @export
multiSelect <- function(inputId, label = NULL, choices = NULL, selected = NULL) {
  args <- lapply(names(choices), function(name) {
    value <- choices[[name]]
    if (value %in% selected) {
      tags$option(value = value, selected = "selected", name)
    } else {
      tags$option(value = value, name)
    }
  })
  args$id = inputId
  args$class = "multiple-select"
  args$multiple = "true"
  tagList(
    singleton(tags$head(
      tags$link(rel = "stylesheet", href = "extdata/multiSelect.css"),
      tags$script(src = "extdata/multiSelect.js")
    )),
    tags$script(paste0("$('#", inputId, "').multipleSelect()")),
    tags$div(
      class = "form-group shiny-input-container",
      tags$label(`for`=inputId, label),
      do.call(tags$select,  args)
    )
  )
}

I've try this:

addResourcePath('extdata', system.file('extdata', package='myPackage'))

I run this in my divosshiny\R\shinyUtils.R file of the package.

but when I run the server and open:

http://127.0.0.1:7003/extdata/multiSelect.js

the multiSelect.js is in package/inst/extdata/ directory. Am I missing something? How addResourcePath is suppose to work?

I don't get any errors when I build the package. I've had errors when I misspelled extdata as exdata so I know that the path is correct.


Solution

  • The function addResourcePath need to be executed in user code (in main server.R), I've added a function:

    #' @export
    setupWidgets <- function() {
      addResourcePath('extdata', system.file('extdata', package='divosShiny'))
    }
    

    and executed it in server.R and it worked.