R 闪亮亮/暗模式开关

L10*_*0Yn 8 r shiny

我有一个基本的 R闪亮应用程序,我想为其构建一个亮/暗模式开关。我想如果我能让它在表格选项卡上工作,那么对于其余的工作应该没问题。我知道shinyjs是最好的方法,但我似乎无法在任何地方找到代码。

library(dplyr)
library(shiny)
library(shinythemes)

ui <- fluidPage(theme = shinytheme("slate"),
                tags$head(tags$style(HTML(
                  "
                  .dataTables_length label,
                  .dataTables_filter label,
                  .dataTables_info {
                      color: white!important;
                      }

                  .paginate_button {
                      background: white!important;
                  }

                  thead {
                      color: white;
                      }

                  "))),
                mainPanel(tabsetPanel(
                  type = "tabs",
                  tabPanel(
                    title = "Table",
                    icon = icon("table"),
                    tags$br(),
                    DT::DTOutput("table")
                  )
                )))

server <- function(input, output) {
  output$table <- DT::renderDT({
    iris
  })
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

dcr*_*olo 5

编辑:见最后的注释

如果您想使用 bootstrap 主题,可以使用复选框输入和添加/删除<link>元素(即加载 bootstrap css 主题的 html 元素)的 javascript 事件来完成此操作。我将其切换shinythemedarkly,因为有相应的浅色主题 ( flatly)。我删除了您定义的 css,tags$head因为它将根据主题切换添加/删除。(参见下面的完整示例)

尽管这有效,但可能存在性能问题。请注意,每次更改主题时,都会获取文件并将其重新加载到浏览器中。主题之间也存在风格差异,这可能会导致应用新主题时内容被重新组织或稍微移动(这可能会对用户造成干扰)。如果您选择这种方法,我建议您找到一个设计良好的浅色和深色主题组合。

或者,您可以选择基本的引导主题并定义您自己的 CSS 主题。您可以使用切换开关(如本示例)或媒体查询prefers-color-scheme。然后shinyjs类函数,您可以从 R 服务器切换主题。人们经常推荐这种方法,但开发和验证确实需要更长的时间。

使用引导方法,您可以按照以下方式切换主题。

应用程序R

在用户界面中,我创建了一个复选框输入并将其放置为最后一个元素(出于示例目的)。

checkboxInput(
  inputId = "themeToggle",
  label = icon("sun")
)
Run Code Online (Sandbox Code Playgroud)

JS

为了切换引导主题,我定义了包定义的 html 依赖路径shinythemes。您可以在 R 包库 ( library/shinythemes/) 中找到它们。

const themes = {
    dark: 'shinythemes/css/darkly.min.css',
    light: 'shinythemes/css/flatly.min.css'
}
Run Code Online (Sandbox Code Playgroud)

要加载新主题,路径需要呈现为 html 元素。我们还需要一个删除现有 CSS 主题的函数。最简单的方法是选择与变量href中定义的匹配的元素themes

// create new <link>
function newLink(theme) {
    let el = document.createElement('link');
    el.setAttribute('rel', 'stylesheet');
    el.setAttribute('text', 'text/css');
    el.setAttribute('href', theme);
    return el;
}

// remove <link> by matching the href attribute
function removeLink(theme) {
    let el = document.querySelector(`link[href='${theme}']`)
    return el.parentNode.removeChild(el);
}
Run Code Online (Sandbox Code Playgroud)

我还删除了 中定义的样式并在 js 中tags$head创建了一个新元素。<style>

// css themes (originally defined in tags$head)
const extraDarkThemeCSS = ".dataTables_length label, .dataTables_filter label, .dataTables_info { color: white!important;} .paginate_button { background: white!important;} thead { color: white;}"

// create new <style> and append css
const extraDarkThemeElement = document.createElement("style");
extraDarkThemeElement.appendChild(document.createTextNode(extraDarkThemeCSS));

// add element to <head>
head.appendChild(extraDarkThemeElement);
Run Code Online (Sandbox Code Playgroud)

最后,我创建了一个事件并将其附加到复选框输入。在此示例中,checked = 'light'unchecked = 'dark'.

toggle.addEventListener('input', function(event) {
    // if checked, switch to light theme
    if (toggle.checked) {
        removeLink(themes.dark);
        head.removeChild(extraDarkThemeElement);
        head.appendChild(lightTheme);

    }  else {
        // else add darktheme
        removeLink(themes.light);
        head.appendChild(extraDarkThemeElement)
        head.appendChild(darkTheme);
    }
})
Run Code Online (Sandbox Code Playgroud)

这是完整的app.R文件。

library(dplyr)
library(shiny)
library(shinythemes)

ui <- fluidPage(
    theme = shinytheme("darkly"),
    mainPanel(
        tabsetPanel(
            type = "tabs",
            tabPanel(
                title = "Table",
                icon = icon("table"),
                tags$br(),
                DT::DTOutput("table")
            )
        ),
        checkboxInput(
            inputId = "themeToggle",
            label = icon("sun")
        )
    ),
    tags$script(
        "
        // define css theme filepaths
        const themes = {
            dark: 'shinythemes/css/darkly.min.css',
            light: 'shinythemes/css/flatly.min.css'
        }

        // function that creates a new link element
        function newLink(theme) {
            let el = document.createElement('link');
            el.setAttribute('rel', 'stylesheet');
            el.setAttribute('text', 'text/css');
            el.setAttribute('href', theme);
            return el;
        }

        // function that remove <link> of current theme by href
        function removeLink(theme) {
            let el = document.querySelector(`link[href='${theme}']`)
            return el.parentNode.removeChild(el);
        }

        // define vars
        const darkTheme = newLink(themes.dark);
        const lightTheme = newLink(themes.light);
        const head = document.getElementsByTagName('head')[0];
        const toggle = document.getElementById('themeToggle');

        // define extra css and add as default
        const extraDarkThemeCSS = '.dataTables_length label, .dataTables_filter label, .dataTables_info {       color: white!important;} .paginate_button { background: white!important;} thead { color: white;}'
        const extraDarkThemeElement = document.createElement('style');
        extraDarkThemeElement.appendChild(document.createTextNode(extraDarkThemeCSS));
        head.appendChild(extraDarkThemeElement);


        // define event - checked === 'light'
        toggle.addEventListener('input', function(event) {
            // if checked, switch to light theme
            if (toggle.checked) {
                removeLink(themes.dark);
                head.removeChild(extraDarkThemeElement);
                head.appendChild(lightTheme);
            }  else {
                // else add darktheme
                removeLink(themes.light);
                head.appendChild(extraDarkThemeElement)
                head.appendChild(darkTheme);
            }
        })
        "
    )
)

server <- function(input, output) {
    output$table <- DT::renderDT({
        iris
    })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

编辑

在这个例子中,我使用了一个checkBoxInput. 您可以使用以下 css 类“隐藏”输入。我建议添加一个视觉上隐藏的文本元素以使该元素易于访问。UI 将更改为以下内容。

checkboxInput(
    inputId = "themeToggle",
    label = tagList(
        tags$span(class = "visually-hidden", "toggle theme"),
        tags$span(class = "fa fa-sun", `aria-hidden` = "true")
    )
)
Run Code Online (Sandbox Code Playgroud)

然后添加下面的css。您还可以使用以下方式选择图标并设置图标样式#themeToggle + span .fa-sun


/* styles for toggle and visually hidden */
#themeToggle, .visually-hidden {
    position: absolute;
    width: 1px;
    height: 1px;
    clip: rect(0 0 0 0);
    clip: rect(0, 0, 0, 0);
    overflow: hidden;
}

/* styles for icon */
#themeToggle + span .fa-sun {
   font-size: 16pt;
}
Run Code Online (Sandbox Code Playgroud)

这是更新后的用户界面。(我删除了js以使示例更短)

ui <- fluidPage(
    theme = shinytheme("darkly"),
    tags$head(
        tags$style(
            "#themeToggle, 
            .visually-hidden {
                position: absolute;
                width: 1px;
                height: 1px;
                clip: rect(0 0 0 0);
                clip: rect(0, 0, 0, 0);
                overflow: hidden;
            }",
            "#themeToggle + span .fa-sun {
                font-size: 16pt;
            }"
        )
    ),
    mainPanel(
        tabsetPanel(
            type = "tabs",
            tabPanel(
                title = "Table",
                icon = icon("table"),
                tags$br(),
                DT::DTOutput("table")
            )
        ),
        checkboxInput(
            inputId = "themeToggle",
            label = tagList(
                tags$span(class = "visually-hidden", "toggle theme"),
                tags$span(class = "fa fa-sun", `aria-hidden` = "true")
            )
        )
    ),
    tags$script("...")
)
Run Code Online (Sandbox Code Playgroud)

  • 很高兴听到。我明白问题出在哪里了。在“const extraDarkThemCSS = ...”行中。选择器“.dataTables_length label”会覆盖选择输入的字体颜色,因为它是嵌套子项。选择输入将继承父属性(即字体颜色)。要解决此问题,请将以下代码添加到 `const extraDarkThemeCss = '....' : `.dataTables_length label select {color: black; }`。我在最后添加了它。使用您喜欢的任何颜色。 (2认同)
  • 我还添加了额外的 css 来“隐藏”复选框。不再需要它,因为图标充当按钮。请参阅上面的编辑 (2认同)