rstudio / shinydashboard

Shiny Dashboarding framework
https://rstudio.github.io/shinydashboard/
Other
886 stars 300 forks source link

FR: expand / collapse menuItems in sidebar when using updateTabItems #347

Open ismirsehregal opened 4 years ago

ismirsehregal commented 4 years ago

Coming from here, I think it would be a good default, that when using updateTabItems the change isn't only affecting the body content but instead also gets visualized in the sidebar.

Current behaviour: screen1

Suggested behaviour: screen

Here is my approch using shinyjs. This however doesn't show the "expanding animation" which can be seen when opening a childful menuItem manually.

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

jsCode <- 'shinyjs.hidemenuItem = function(targetid) {var x = document.getElementById(targetid); x.style.display = "none"; x.classList.remove("menu-open");};
shinyjs.showmenuItem = function(targetid) {var x = document.getElementById(targetid); x.style.display = "block"; x.classList.add("menu-open");};'

ui <- dashboardPage(
  dashboardHeader(title = "Expand menuItems"),
  dashboardSidebar(
    sidebarMenu(
      id = "sidebarID",
      menuItem("mainItem1", id = "mainItem1ID", tabName = "mainItem1", icon = icon("dashboard"), menuSubItem("subItem1", tabName = "subItem1")),
      menuItem("mainItem2", id = "mainItem2ID", tabName = "mainItem2", icon = icon("th"), menuSubItem("subItem2", tabName = "subItem2"))
    ),
    actionButton(inputId = "toggleTab", label = "Toggle Tab")
  ),

  dashboardBody(
    useShinyjs(),
    extendShinyjs(text = jsCode, functions = c("hidemenuItem", "showmenuItem")),
    tabItems(
      tabItem(tabName = "subItem1", "subItem1 content"),
      tabItem(tabName = "subItem2", "subItem2 content")
    )
  )
)

server <- function(input, output, session){

  observeEvent(input$toggleTab, {
    targetID <- paste0("mainItem", input$toggleTab%%2+1, "ID")
    js$hidemenuItem(setdiff(c("mainItem1ID", "mainItem2ID"), targetID))
    js$showmenuItem(targetID)
    updateTabItems(session, inputId="sidebarID", selected = paste0("subItem", input$toggleTab%%2+1))
  })

}

shinyApp(ui, server)

Edit: updated code according to @Crparedes' comment.

Crparedes commented 2 years ago

From a new update of shinyjs package, the function extendShinyjs requires functions argument. Therefore extendShinyjs(text = jsCode, functions = c("hidemenuItem", "showmenuItem")), shall be used instead of extendShinyjs(text = jsCode),

YongbingDing commented 2 years ago

您好,丁永兵已经收到您的邮件,谢谢。