如何从服务器端检查一个闪亮的仪表板框是否已折叠

4
我正在尝试找到一种方法来检查Shiny Dashboard Box是否已折叠或展开。
通过阅读@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)  

通过检查UI HTML,我发现解决我的问题的答案可能是通过访问图标类(以查看它是否为fa fa-plus或fa fa-minus)来解决的,但我不知道该如何做。任何帮助将不胜感激。干杯!

shinydashboardPlus::box() 提供了相应的状态信息:input$mybox$collapsed - undefined
1个回答

6
您可以创建一个新的输入框,当用户折叠该框时触发,类似于以下内容:
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)  

如果您愿意,可以在调用 Shiny.onInputChange 时通过将 'collapse'/'expanded' 更改为 true/false 来更改内容。


非常感谢@Victorp,我永远也想不到那个! - JesperHansen
现在 extendShinyjs(text = jscode, functions = c("collapse")) 可以正常工作了。 - YBS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接