posit-dev / r-shinylive

https://posit-dev.github.io/r-shinylive/
Other
151 stars 16 forks source link

Usage of global.R #18

Closed stla closed 11 months ago

stla commented 11 months ago

Hello,

ShinyLive is very cool, thank you for the work.

I made an app app.R accompanied with a global.R file but global.R is not executed. I tried to put it at first position in the JSON file but that does not solve the problem. If it is not possible to use global.R, it would be nice to add this feature. If it is possible, how?

schloerke commented 11 months ago

@stla I have tried to recreate an app with a global.R and an app.R and I could not get global.R to be automatically called with an app.R file with regular shiny.

Unexpected behavior reprex:

./app.R

library(shiny)

shinyApp(
    fluidPage(
        sliderInput("n", "Global value: N", 0, 100, global_value),
        verbatimTextOutput("txt", placeholder = TRUE),
    ),
    function(input, output) {
        output$txt <- renderText({
            paste0("The value of n*2 is ", 2 * input$n)
        })
    }
)

./global.R

global_value <- 50
schloerke commented 11 months ago

However, when using ui.R and server.R, global.R is sourced.

Fix

These lines will need to be changed to:

  if (!(
    fs::file_exists(fs::path(appdir, "app.R")) ||
      fs::file_exists(fs::path(appdir, "server.R"))
  )) {
    stop("Directory ", appdir, " does not contain an app.R or server.R file.")
  }

Working reprex with fix:

./server.R

library(shiny)

fluidPage(
    sliderInput("n", "Global value: N", 0, 100, global_value),
    verbatimTextOutput("txt", placeholder = TRUE),
)

./ui.R

fluidPage(
    sliderInput("n", "Global value: N", 0, 100, global_value),
    verbatimTextOutput("txt", placeholder = TRUE),
)

./global.R

global_value <- 50
stla commented 11 months ago

Wow, I prefer the ui.R + server.R way, I didn't know it was possible with ShinyLive! Thanks!