Search code examples
rshinybslib

How to set up an event which expands a bslib card?


I would like to expand a bslib card in a shiny app from the server. Here is a minimal example:

library(shiny)
library(bslib)

ui <- bslib::page_fluid(
  actionButton("go", "GO"),
  bslib::card(
    h1("Hello"),
    full_screen = TRUE
    )
)

server <- function(input, output, session){
  observe({
    # some code to expand the card 
  }) |> 
    bindEvent(input$go)
}

shinyApp(ui, server)


Solution

  • You can use session$sendCustomMessage and a handler which simulates a click on the "Expand" button:

    library(shiny)
    library(bslib)
    
    ui <- bslib::page_fluid(
      tags$head(tags$script(HTML(
        "Shiny.addCustomMessageHandler('expand',",
        "  function(message) {",
        "    $('#' + message.id + ' > bslib-tooltip > button').click();",
        "  }",
        ");"))),
      actionButton("go", "GO"),
      bslib::card(
        id = "my_card",
        h1("Hello"),
        full_screen = TRUE
      )
    )
    
    server <- function(input, output, session){
      observeEvent(input$go, {
        session$sendCustomMessage(type = 'expand', message = list(id = "my_card"))
      })
    }
    
    shinyApp(ui, server)
    

    enter image description here