bslib card only render content when in full screen

134 views Asked by At

I'm using bslib for my shiny UI. I have a bunch of cards where full_screen = TRUE. When a card is expanded to full screen, I want it to render a table. I only want it to render the table when in full screen mode. How can I achieve this?

Here's some reprex code:

library(shiny)
library(bslib)
library(DT)
library(purrr)

datasets <- list(
  Iris = iris, Mtcars = mtcars, Volcanos = volcano,
  `Chick Weights` = chickwts, Earthquakes = quakes, 
  `US Arrests` = USArrests, `C02` = co2, `Air Quality` = airquality
)

ui <- page_fillable(
  uiOutput("cards")
)

server <- function(input, output) {
  
  output$cards <- renderUI({
    
    card_list <- imap(datasets, ~{
      card(
        card_header(.y),
        card_body(
          datatable(head(as.data.frame(.x)))
        ),
        full_screen = TRUE,
        height = 200
      )
    }) |> 
      unname()
    
    # I only want the table to show when in full screen
    layout_columns(
      !!!card_list
    )
  })
}

shinyApp(ui = ui, server = server)

In this example, the DT tables always render, even when the card is small. I only want the tables to render when the card is full screen. In my actual use case, the table will be populated by a database call, so I want it to be lazy too (i.e., only build the table when the card is expanded).

1

There are 1 answers

0
Stéphane Laurent On

You can use getCurrentOutputInfo. Here is an example with a plot:

library(shiny)
library(bslib)
library(ggplot2)

# UI logic
ui <- page_fluid(
  card(
    max_height = 200,
    full_screen = TRUE,
    card_header("A dynamically rendered plot"),
    plotOutput("plot_id")
  )
)

# Server logic
server <- function(input, output, session) {
  output$plot_id <- renderPlot({
    info <- getCurrentOutputInfo()
    if (info$height() > 200) {
      ggplot(mtcars, aes(wt, mpg)) +
        geom_point() 
    } 
  })
}

shinyApp(ui, server)

enter image description here