rstudio / shiny

Easy interactive web applications with R
http://shiny.rstudio.com
Other
5.3k stars 1.87k forks source link

session$setCurrentTheme(bs_theme): confusing behaviour+error message regarding version #4081

Open daattali opened 1 month ago

daattali commented 1 month ago

It's reasonable to expect the following to work:

library(shiny)

ui <- fluidPage(
  selectInput("mode", "mode", c("light", "dark"))
)

server <- function(input, output, session) {
  observeEvent(input$mode, {
    if (input$mode == "light") {
      session$setCurrentTheme(bslib::bs_theme(bg="white", fg="black"))
    } else {
      session$setCurrentTheme(bslib::bs_theme(bg="black", fg="white"))
    }
  })
}

shinyApp(ui, server)

It results in the following error:

Error in : session$setCurrentTheme() cannot be used to change the Bootstrap version from  to 5. Try using `bs_theme(version = 5)` for initial theme.

I find two issues with the error message:

  1. Because no theme was initially explicitly set, the text says "version from to 5". Grammar is incorrect, a number is missing there
  2. The solution of trying to use bs_theme(version=5) for initial theme is pointing in the right direction, but it's a little unclear where you should be using that function call. It would be much better if it said that you need to make this call in the UI definition of the page.

But in my opinion this behaviour in itself suboptimal and has two large problems from a UX perspective:

  1. I should be able to use bslib::bs_theme() to change one aspect of the theme at some point in the app regardless of whether or not I made a call in the UI with a version number. The above code should just work. Currently shiny uses bootstrap3 by default, so it should just assume that version 3 is used if none is explicitly given.
  2. Even if I did make a call in the UI to initialize to bootstrap version 3, the above code would still fail, because it would say I'm trying to change from v3 to v5. There's a usability problem in that, because it means that every single time I call bs_theme() I'm expected to repeat the version number. I think if no version is provided to the function, then it should just use the last version used.

Slightly off topic, but it's also a bit unclear IMO that shiny uses version 3 by default, but if you call bs_theme() it'll default to 5 -- I understand it, but I think it can be very confusing what is meant by "default version" when there are two meanings to it.