如何查看闪亮的仪表板框是否从服务器端折叠仪表板、服务器端

2023-09-03 14:03:00 作者:12.故人听雨

我正在尝试找到一种方法来检查闪亮的仪表板框是折叠还是展开。

通过阅读How to manually collapse a box in shiny dashboard中@daattali的伟大回复,我知道可以使用shinyjs包从服务器端折叠盒子,如下面的代码所示

library(shiny)
library(shinydashboard)
library(shinyjs)

jscode <- "
shinyjs.collapse = function(boxid) {
$('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
}
"

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    extendShinyjs(text = jscode),
    actionButton("bt1", "Collapse box1"),
    actionButton("bt2", "Collapse box2"),
    br(), br(),
    box(id = "box1", collapsible = TRUE, p("Box 1")),
    box(id = "box2", collapsible = TRUE, p("Box 2"))
  )
)

server <- function(input, output) {
  observeEvent(input$bt1, {
    js$collapse("box1")
  })
  observeEvent(input$bt2, {
    js$collapse("box2")
  })
}

shinyApp(ui, server)  
server2012 仪表板 本地服务器是红色

通过检查UI HTML,我发现我的问题的答案可以通过访问图标类来解决(查看它是FA-+还是FA--),但我不知道如何做到这一点。

任何帮助都将不胜感激。

干杯

推荐答案

您可以创建一个新的输入,在用户折叠框时触发,如下所示:

collapseInput <- function(inputId, boxId) {
  tags$script(
    sprintf(
      "$('#%s').closest('.box').on('hidden.bs.collapse', function () {Shiny.onInputChange('%s', true);})",
      boxId, inputId
    ),
    sprintf(
      "$('#%s').closest('.box').on('shown.bs.collapse', function () {Shiny.onInputChange('%s', false);})",
      boxId, inputId
    )
  )
}

举个例子:

library(shiny)
library(shinydashboard)
library(shinyjs)

jscode <- "
shinyjs.collapse = function(boxid) {
$('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
}
"
collapseInput <- function(inputId, boxId) {
  tags$script(
    sprintf(
      "$('#%s').closest('.box').on('hidden.bs.collapse', function () {Shiny.onInputChange('%s', true);})",
      boxId, inputId
    ),
    sprintf(
      "$('#%s').closest('.box').on('shown.bs.collapse', function () {Shiny.onInputChange('%s', false);})",
      boxId, inputId
    )
  )
}


ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    extendShinyjs(text = jscode),
    actionButton("bt1", "Collapse box1"),
    actionButton("bt2", "Collapse box2"),
    br(), br(),
    box(id = "box1", collapsible = TRUE, p("Box 1")),
    box(id = "box2", collapsible = TRUE, p("Box 2")),
    collapseInput(inputId = "iscollapsebox1", boxId = "box1"),
    verbatimTextOutput(outputId = "res")
  )
)

server <- function(input, output) {
  observeEvent(input$bt1, {
    js$collapse("box1")
  })
  observeEvent(input$bt2, {
    js$collapse("box2")
  })

  output$res <- renderPrint({
    input$iscollapsebox1
  })
}

shinyApp(ui, server)  

如果需要,可以在函数collapseInput调用Shiny.onInputChange时,通过'collapse'/'expanded'更改true/false