rshinydashboardsidebarbs4dash

How to display a shorter title if the sidebar is collapsed?


I have a bs4Dash dashboard. In this I have a long title: 'ABC - Controll System'. This title is also displayed correctly:

enter image description here

Now I want to display the short title "ABC" when I collapse the sidebar:

enter image description here

Here is my reproducible example:

library(shiny)
library(bs4Dash)

shinyApp(
  ui = dashboardPage(
    title = "Basic Dashboard",
    header = dashboardHeader(
      title = dashboardBrand(
        title = div(HTML("<strong>ABC</strong> - Controll System"), style="text-align: center;"),
        color = "primary"
      )
      ),
    sidebar = dashboardSidebar(),
    controlbar = dashboardControlbar(),
    footer = dashboardFooter(),
    body = dashboardBody()
  ),
  server = function(input, output) {}
)

Can someone help me?


Solution

  • A solution using css and js:

    enter image description here

    library(shiny)
    library(bs4Dash)
    
    css <- c(
      ".sidebar-mini.sidebar-collapse .brand-text {",
      "  all: unset;",
      "}",
      "[class*='sidebar-light'] .brand-link {",
      "  text-align: center;",
      "}"
    )
    
    js <- c(
      "document.addEventListener('DOMContentLoaded', function(event) {",
        "var element = document.querySelector('body');",
        "new MutationObserver((mutations) => {",
          "document.querySelector('.brand-text').innerHTML = ",
          "  (mutations[0].target.classList.contains('sidebar-collapse')) ?",
          "  '<strong>ABC</strong>' :",
          "  '<strong>ABC</strong> - Controll System';",
        "})",
        ".observe(element, {",
        "  attributes: true ",
        "});",
      "});"
    )
    
    ui <- dashboardPage(
      title = "Basic Dashboard",
      header = dashboardHeader(title = dashboardBrand(
        title = "test",
        color = "primary"
      )),
      sidebar = dashboardSidebar(
        tags$head(tags$style(HTML(css)),
                  tags$script(HTML(js)))
      ),
      controlbar = dashboardControlbar(),
      footer = dashboardFooter(),
      body = dashboardBody()
    )
    
    shinyApp(ui, \(...) {})