Отображать другое изображение в качестве заголовка блестящей панели инструментов на основе разных панелей - PullRequest
0 голосов
/ 28 марта 2020

Можно ли отобразить другое изображение в качестве заголовка блестящей панели инструментов в зависимости от tabPanel(), который вы используете. Я хочу другое изображение для вкладки 'Front' и другое для вкладки 'Data'.

# app.R ##
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(DT)
library(shinyWidgets)
library(shinyjs)

dbHeader <- dashboardHeaderPlus(
  enable_rightsidebar = TRUE,
  rightSidebarIcon = "gears",
  fixed = T,
  title = tags$a(href='http://mycompanyishere.com',
                                 tags$img(src='logo.png'))
)

ui <- dashboardPagePlus(
  dbHeader,
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    tags$hr(),
    tabsetPanel(
      id ="tabA",
      type = "tabs",
      tabPanel("Front",icon = icon("accusoft")),
      tabPanel("Data", icon = icon("table")
      )
    )
  ),
  rightsidebar = rightSidebar()
)

server <- function(input, output) {
  observe({
    if (input$tabA == "Front") {
      hide(selector = "body > div.wrapper > header > nav > div:nth-child(4) > ul")
      addClass(selector = "body", class = "sidebar-collapse")
      removeClass(selector = "body", class = "control-sidebar-open")
    } else {
      show(selector = "body > div.wrapper > header > nav > div:nth-child(4) > ul")
      removeClass(selector = "body", class = "sidebar-collapse")
      addClass(selector = "body", class = "control-sidebar-open")
    }
  })
}

shinyApp(ui = ui, server = server)

1 Ответ

1 голос
/ 01 апреля 2020

Таким образом, один из способов добиться этого - использовать блестящий js и изменить CSS в блестящем реактивном выводе.

Для этого я сначала «позаимствовал» эту функцию

# This part is from the link below and will be used to modify CSS in reactive part
# https://stackoverflow.com/questions/31425841/css-for-each-page-in-r-shiny
modifyStyle <- function(selector, ...) {

  values <- as.list(substitute(list(...)))[-1L]
  parameters <- names(values)

  args <- Map(function(p, v) paste0("'", p,"': '", v,"'"), parameters, values)
  jsc <- paste0("$('",selector,"').css({", paste(args, collapse = ", "),"});")

  shinyjs::runjs(code = jsc)

}

И затем, используя две функции ниже (внутри observe() функция в серверная часть ) Я изменил CSS в реактивном выводе, используя CSS код:

# Show one picture. 
# NOTE:if using your own picture modify the path inside url().. See the code below.
      modifyStyle(".logo img ", "content" = "url(https://dotunroy.files.wordpress.com/2015/05/happy-people.jpg)")
# Show another picture
  modifyStyle(".logo img ", "content" = "url(test.png)")

Обратите внимание , что для того, чтобы я мог показать, что код работает, сначала мне нужно было сделать несколько картинок. Итак, я сохранил одно изображение внутри моего www directory (изображение называется test.png (см. Приведенный выше код)). И другой доступен по этой ссылке https://dotunroy.files.wordpress.com/2015/05/happy-people.jpg.

Таким образом, весь код выглядит следующим образом (опять же, для того, чтобы вы отображали изображения, замените путь моих изображений внутри URL ( ) с вашим собственным)

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(DT)
library(shinyWidgets)
library(shinyjs)
# Modify the CSS style of a given selector

# This part is from 
# https://stackoverflow.com/questions/31425841/css-for-each-page-in-r-shiny
modifyStyle <- function(selector, ...) {

  values <- as.list(substitute(list(...)))[-1L]
  parameters <- names(values)

  args <- Map(function(p, v) paste0("'", p,"': '", v,"'"), parameters, values)
  jsc <- paste0("$('",selector,"').css({", paste(args, collapse = ", "),"});")

  shinyjs::runjs(code = jsc)

}


dbHeader <- dashboardHeaderPlus(
  enable_rightsidebar = TRUE,
  rightSidebarIcon = "gears",
  fixed = T,
  title = tags$a(href='http://mycompanyishere.com',
# Modify the width and the height of the image as you like
                 tags$img(src='test.png', width ="50%", height = "70%"))
)

ui <- dashboardPagePlus(
  dbHeader,
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    tags$hr(),
    tabsetPanel(
      id ="tabA",
      type = "tabs",
      tabPanel("Front",icon = icon("accusoft")),
      tabPanel("Data", icon = icon("table")
      )
    )
  ),
  rightsidebar = rightSidebar()
)

server <- function(input, output) {
  observe({
    if (input$tabA == "Front") {
      hide(selector = "body > div.wrapper > header > nav > div:nth-child(4) > ul")
      addClass(selector = "body", class = "sidebar-collapse")
      removeClass(selector = "body", class = "control-sidebar-open")
      modifyStyle(".logo img ", "content" = "url(https://dotunroy.files.wordpress.com/2015/05/happy-people.jpg)")
      # shinyjs::toggleClass(selector = "head", class = "logo",
      #                      condition = (input$tabA == "Front"))
    } else {
      show(selector = "body > div.wrapper > header > nav > div:nth-child(4) > ul")
      removeClass(selector = "body", class = "sidebar-collapse")
      addClass(selector = "body", class = "control-sidebar-open")
      modifyStyle(".logo img ", "content" = "url(test.png)")


    }
  })
}

shinyApp(ui = ui, server = server)

И вывод:

enter image description here

ОБНОВЛЕНИЕ Обратите внимание, что если Вы хотите изменить width и height изображения, просто добавьте эти два параметра в CSS, то есть

   # Add a custom number of the percentage to width and height parameters
      modifyStyle(".logo img ", "content" = 
    "url(https://dotunroy.files.wordpress.com/2015/05/happy-people.jpg)",
     "width" = "100%", "height" = "100%")
...