Title: | Custom 'Bootstrap' 'Sass' Themes for 'shiny' and 'rmarkdown' |
---|---|
Description: | Simplifies custom 'CSS' styling of both 'shiny' and 'rmarkdown' via 'Bootstrap' 'Sass'. Supports 'Bootstrap' 3, 4 and 5 as well as their various 'Bootswatch' themes. An interactive widget is also provided for previewing themes in real time. |
Authors: | Carson Sievert [aut, cre] , Joe Cheng [aut], Garrick Aden-Buie [aut] , Posit Software, PBC [cph, fnd], Bootstrap contributors [ctb] (Bootstrap library), Twitter, Inc [cph] (Bootstrap library), Javi Aguilar [ctb, cph] (Bootstrap colorpicker library), Thomas Park [ctb, cph] (Bootswatch library), PayPal [ctb, cph] (Bootstrap accessibility plugin) |
Maintainer: | Carson Sievert <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.8.0.9000 |
Built: | 2024-11-19 21:21:48 UTC |
Source: | https://github.com/rstudio/bslib |
An accordion can be used to organize UI elements and content in a limited
space. It comprises multiple, vertically stacked panels that expand or
collapse when clicked, providing a compact layout that works well for
grouping input elements in a sidebar()
or for organizing detailed
context-specific information.
accordion( ..., id = NULL, open = NULL, multiple = TRUE, class = NULL, width = NULL, height = NULL ) accordion_panel(title, ..., value = title, icon = NULL)
accordion( ..., id = NULL, open = NULL, multiple = TRUE, class = NULL, width = NULL, height = NULL ) accordion_panel(title, ..., value = title, icon = NULL)
... |
Named arguments become attributes on the |
id |
If provided, you can use |
open |
A character vector of |
multiple |
Whether multiple |
class |
Additional CSS classes to include on the accordion div. |
width , height
|
Any valid CSS unit; for example, height="100%". |
title |
A title to appear in the |
value |
A character string that uniquely identifies this panel. |
icon |
A htmltools::tag child (e.g., |
bslib's accordion component is derived from the Bootstrap Accordion component. Accordions are also featured on the bslib website:
accordion_panel_set()
, accordion_panel_open()
and
accordion_panel_close()
programmatically interact with the state of an
accordion panel.
accordion_panel_insert()
, accordion_panel_remove()
and
accordion_panel_update()
add or remove accordion panels from an
accordion.
Other Components:
card()
,
popover()
,
tooltip()
,
value_box()
items <- lapply(LETTERS, function(x) { accordion_panel(paste("Section", x), paste("Some narrative for section", x)) }) # First shown by default accordion(!!!items) # Nothing shown by default accordion(!!!items, open = FALSE) # Everything shown by default accordion(!!!items, open = TRUE) # Show particular sections accordion(!!!items, open = "Section B") accordion(!!!items, open = c("Section A", "Section B")) # Provide an id to create a shiny input binding library(shiny) ui <- page_fluid( accordion(!!!items, id = "acc") ) server <- function(input, output) { observe(print(input$acc)) } shinyApp(ui, server)
items <- lapply(LETTERS, function(x) { accordion_panel(paste("Section", x), paste("Some narrative for section", x)) }) # First shown by default accordion(!!!items) # Nothing shown by default accordion(!!!items, open = FALSE) # Everything shown by default accordion(!!!items, open = TRUE) # Show particular sections accordion(!!!items, open = "Section B") accordion(!!!items, open = c("Section A", "Section B")) # Provide an id to create a shiny input binding library(shiny) ui <- page_fluid( accordion(!!!items, id = "acc") ) server <- function(input, output) { observe(print(input$acc)) } shinyApp(ui, server)
Dynamically update/modify accordion()
s in a Shiny app. To be updated
programmatically, the accordion()
must have an id
. These functions
require an active Shiny session and only work with a running Shiny app.
accordion_panel_set(id, values, session = get_current_session()) accordion_panel_open(id, values, session = get_current_session()) accordion_panel_close(id, values, session = get_current_session()) accordion_panel_insert( id, panel, target = NULL, position = c("after", "before"), session = get_current_session() ) accordion_panel_remove(id, target, session = get_current_session()) accordion_panel_update( id, target, ..., title = NULL, value = NULL, icon = NULL, session = get_current_session() )
accordion_panel_set(id, values, session = get_current_session()) accordion_panel_open(id, values, session = get_current_session()) accordion_panel_close(id, values, session = get_current_session()) accordion_panel_insert( id, panel, target = NULL, position = c("after", "before"), session = get_current_session() ) accordion_panel_remove(id, target, session = get_current_session()) accordion_panel_update( id, target, ..., title = NULL, value = NULL, icon = NULL, session = get_current_session() )
id |
an character string that matches an existing |
values |
either a character string (used to identify particular
|
session |
a shiny session object (the default should almost always be used). |
panel |
|
target |
The |
position |
Should |
... |
Elements that become the new content of the panel. |
title |
A title to appear in the |
value |
A character string that uniquely identifies this panel. |
icon |
A htmltools::tag child (e.g., |
accordion_panel_set()
: same as accordion_panel_open()
, except it
also closes any currently open panels.
accordion_panel_open()
: open accordion_panel()
s.
accordion_panel_close()
: close accordion_panel()
s.
accordion_panel_insert()
: insert a new accordion_panel()
accordion_panel_remove()
: remove accordion_panel()
s.
accordion_panel_update()
: update a accordion_panel()
.
accordion()
and accordion_panel()
create the accordion
component.
Filling layouts in bslib are built on the foundation of fillable containers
and fill items (fill carriers are both fillable and fill). This is why most
bslib components (e.g., card()
, card_body()
, layout_sidebar()
) possess
both fillable
and fill
arguments (to control their fill behavior).
However, sometimes it's useful to add, remove, and/or test fillable/fill
properties on arbitrary htmltools::tag()
, which these functions are
designed to do.
as_fill_carrier( x, ..., min_height = NULL, max_height = NULL, gap = NULL, class = NULL, style = NULL, css_selector = NULL ) as_fillable_container( x, ..., min_height = NULL, max_height = NULL, gap = NULL, class = NULL, style = NULL, css_selector = NULL ) as_fill_item( x, ..., min_height = NULL, max_height = NULL, class = NULL, style = NULL, css_selector = NULL ) remove_all_fill(x) is_fill_carrier(x) is_fillable_container(x) is_fill_item(x)
as_fill_carrier( x, ..., min_height = NULL, max_height = NULL, gap = NULL, class = NULL, style = NULL, css_selector = NULL ) as_fillable_container( x, ..., min_height = NULL, max_height = NULL, gap = NULL, class = NULL, style = NULL, css_selector = NULL ) as_fill_item( x, ..., min_height = NULL, max_height = NULL, class = NULL, style = NULL, css_selector = NULL ) remove_all_fill(x) is_fill_carrier(x) is_fillable_container(x) is_fill_item(x)
x |
An |
... |
Currently ignored. |
min_height , max_height
|
Any valid CSS unit
(e.g., |
gap |
Any valid CSS unit. |
class |
A character vector of class names to add to the tag. |
style |
A character vector of CSS properties to add to the tag. |
css_selector |
A character string containing a CSS selector for
targeting particular (inner) tag(s) of interest. For more details on what
selector(s) are supported, see |
Although as_fill()
, as_fillable()
, and as_fill_carrier()
can work with
non-tag objects that have a htmltools::as.tags method (e.g., htmlwidgets),
they return the "tagified" version of that object.
For as_fill()
, as_fillable()
, and as_fill_carrier()
: the tagified
version x
, with relevant tags modified to possess the relevant fill
properties.
For is_fill()
, is_fillable()
, and is_fill_carrier()
: a logical vector,
with length matching the number of top-level tags that possess the relevant
fill properties.
The Filling Layouts article on the bslib website introduces the concept of fillable containers and fill items.
These functions provide a convenient interface to the underlying
htmltools::bindFillRole()
function.
library(shiny) shinyApp( page_fillable( # without `as_fill_carrier()`, the plot won't fill the page because # `uiOutput()` is neither a fillable container nor a fill item by default. as_fill_carrier(uiOutput("ui")) ), function(input, output) { output$ui <- renderUI({ div( class = "bg-info text-white", as_fill_item(), "A fill item" ) }) } )
library(shiny) shinyApp( page_fillable( # without `as_fill_carrier()`, the plot won't fill the page because # `uiOutput()` is neither a fillable container nor a fill item by default. as_fill_carrier(uiOutput("ui")) ), function(input, output) { output$ui <- renderUI({ div( class = "bg-info text-white", as_fill_item(), "A fill item" ) }) } )
input_task_button
to ExtendedTask
Sets up a shiny::ExtendedTask to relay its state to an existing
input_task_button()
, so the task button stays in its "busy" state for as
long as the extended task is running.
Note that bind_task_button
does not automatically cause button presses to
invoke the extended task; you still need to use shiny::bindEvent()
(or
shiny::observeEvent()
) to cause the button press to trigger an invocation,
as in the example below.
bind_task_button
cannot be used to bind one task button to multiple
ExtendedTask
objects; if you attempt to do so, any bound ExtendedTask
that completes will cause the button to return to "ready" state.
bind_task_button(target, task_button_id, ...) ## Default S3 method: bind_task_button(target, task_button_id, ...) ## S3 method for class 'ExtendedTask' bind_task_button(target, task_button_id, ..., session = get_current_session())
bind_task_button(target, task_button_id, ...) ## Default S3 method: bind_task_button(target, task_button_id, ...) ## S3 method for class 'ExtendedTask' bind_task_button(target, task_button_id, ..., session = get_current_session())
target |
The target object (i.e. |
task_button_id |
A string matching the |
... |
Further arguments passed to other methods. |
session |
A Shiny session object (the default should almost always be used). |
The target
object that was passed in.
library(shiny) library(bslib) library(future) plan(multisession) ui <- page_sidebar( sidebar = sidebar( input_task_button("recalc", "Recalculate") ), textOutput("outval") ) server <- function(input, output) { rand_task <- ExtendedTask$new(function() { future({ # Slow operation goes here Sys.sleep(2) runif(1) }, seed = TRUE) }) # Make button state reflect task. # If using R >=4.1, you can do this instead: # rand_task <- ExtendedTask$new(...) |> bind_task_button("recalc") bind_task_button(rand_task, "recalc") observeEvent(input$recalc, { rand_task$invoke() }) output$outval <- renderText({ rand_task$result() }) } shinyApp(ui, server)
library(shiny) library(bslib) library(future) plan(multisession) ui <- page_sidebar( sidebar = sidebar( input_task_button("recalc", "Recalculate") ), textOutput("outval") ) server <- function(input, output) { rand_task <- ExtendedTask$new(function() { future({ # Slow operation goes here Sys.sleep(2) runif(1) }, seed = TRUE) }) # Make button state reflect task. # If using R >=4.1, you can do this instead: # rand_task <- ExtendedTask$new(...) |> bind_task_button("recalc") bind_task_button(rand_task, "recalc") observeEvent(input$recalc, { rand_task$invoke() }) output$outval <- renderText({ rand_task$result() }) } shinyApp(ui, server)
Obtain a list of all available bootswatch themes.
bootswatch_themes(version = version_default(), full_path = FALSE)
bootswatch_themes(version = version_default(), full_path = FALSE)
version |
The major version of Bootswatch. |
full_path |
Whether to return a path to the installed theme. |
Returns a character vector of Bootswatch themes.
Other Bootstrap theme utility functions:
bs_get_variables()
,
builtin_themes()
,
theme_bootswatch()
,
theme_version()
,
versions()
A generic constructor for responsive breakpoints.
breakpoints(..., xs = NULL, sm = NULL, md = NULL, lg = NULL)
breakpoints(..., xs = NULL, sm = NULL, md = NULL, lg = NULL)
... |
Other breakpoints (e.g., |
xs |
The default value to apply to the |
sm |
Values to apply at the |
md |
Values to apply at the |
lg |
Values to apply at the |
Bootstrap's Breakpoints article provides more detail on breakpoints and how they are used and customized.
breakpoints()
is used by layout_columns()
.
breakpoints(sm = c(4, 4, 4), md = c(3, 3, 6), lg = c(-2, 8, -2))
breakpoints(sm = c(4, 4, 4), md = c(3, 3, 6), lg = c(-2, 8, -2))
These functions provide direct access to the layers of a bslib theme created
with bs_theme()
. Learn more about composable Sass layers on the
sass website.
bs_add_variables( theme, ..., .where = "defaults", .default_flag = identical(.where, "defaults") ) bs_add_rules(theme, rules) bs_add_functions(theme, functions) bs_add_mixins(theme, mixins) bs_bundle(theme, ...)
bs_add_variables( theme, ..., .where = "defaults", .default_flag = identical(.where, "defaults") ) bs_add_rules(theme, rules) bs_add_functions(theme, functions) bs_add_mixins(theme, mixins) bs_bundle(theme, ...)
theme |
A |
... |
|
.where |
Whether to place the variable definitions before other Sass
|
.default_flag |
Whether or not to add a |
rules |
Sass rules. Anything understood by |
functions |
A character vector or |
mixins |
A character vector or |
Compared to higher-level theme customization available in bs_theme()
, these
functions are a more direct interface to Bootstrap Sass, and therefore, do
nothing to ensure theme customizations are portable between major Bootstrap
versions.
Returns a modified bs_theme()
object.
bs_add_variables()
: Add Bootstrap Sass
variable defaults.
bs_add_rules()
: Add additional
Sass rules.
bs_add_functions()
: Add additional Sass functions.
bs_add_mixins()
: Add additional Sass mixins.
bs_bundle()
: Add additional sass::sass_bundle()
objects to an
existing theme
.
bslib's theming capabilities are powered by the sass package.
Learn more about composable Sass layers on the sass website.
bs_theme()
creates a Bootstrap theme object, and is the best place
to start learning about bslib's theming capabilities.
Other Bootstrap theme functions:
bs_current_theme()
,
bs_dependency()
,
bs_global_theme()
,
bs_remove()
,
bs_theme()
,
bs_theme_dependencies()
,
bs_theme_preview()
# Function to preview the styling a (primary) Bootstrap button library(htmltools) button <- tags$a(class = "btn btn-primary", href = "#", role = "button", "Hello") preview_button <- function(theme) { browsable(tags$body(bs_theme_dependencies(theme), button)) } # Here we start with a theme based on a Bootswatch theme, # then override some variable defaults theme <- bs_add_variables( bs_theme(bootswatch = "sketchy", primary = "orange"), "body-bg" = "#EEEEEE", "font-family-base" = "monospace", "font-size-base" = "1.4rem", "btn-padding-y" = ".16rem", "btn-padding-x" = "2rem" ) preview_button(theme) # If you need to set a variable based on another Bootstrap variable theme <- bs_add_variables(theme, "body-color" = "$success", .where = "declarations") preview_button(theme) # Start a new global theme and add some custom rules that # use Bootstrap variables to define a custom styling for a # 'person card' person_rules <- system.file("custom", "person.scss", package = "bslib") theme <- bs_add_rules(bs_theme(), sass::sass_file(person_rules)) # Include custom CSS that leverages bootstrap Sass variables person <- function(name, title, company) { tags$div( class = "person", h3(class = "name", name), div(class = "title", title), div(class = "company", company) ) } page_fluid( theme = theme, person("Andrew Carnegie", "Owner", "Carnegie Steel Company"), person("John D. Rockefeller", "Chairman", "Standard Oil") )
# Function to preview the styling a (primary) Bootstrap button library(htmltools) button <- tags$a(class = "btn btn-primary", href = "#", role = "button", "Hello") preview_button <- function(theme) { browsable(tags$body(bs_theme_dependencies(theme), button)) } # Here we start with a theme based on a Bootswatch theme, # then override some variable defaults theme <- bs_add_variables( bs_theme(bootswatch = "sketchy", primary = "orange"), "body-bg" = "#EEEEEE", "font-family-base" = "monospace", "font-size-base" = "1.4rem", "btn-padding-y" = ".16rem", "btn-padding-x" = "2rem" ) preview_button(theme) # If you need to set a variable based on another Bootstrap variable theme <- bs_add_variables(theme, "body-color" = "$success", .where = "declarations") preview_button(theme) # Start a new global theme and add some custom rules that # use Bootstrap variables to define a custom styling for a # 'person card' person_rules <- system.file("custom", "person.scss", package = "bslib") theme <- bs_add_rules(bs_theme(), sass::sass_file(person_rules)) # Include custom CSS that leverages bootstrap Sass variables person <- function(name, title, company) { tags$div( class = "person", h3(class = "name", name), div(class = "title", title), div(class = "company", company) ) } page_fluid( theme = theme, person("Andrew Carnegie", "Owner", "Carnegie Steel Company"), person("John D. Rockefeller", "Chairman", "Standard Oil") )
Intended for advanced use by developers to obtain the currently active theme
at render time and primarily for implementing themable widgets that can't
otherwise be themed via bs_dependency_defer()
.
bs_current_theme(session = get_current_session(FALSE))
bs_current_theme(session = get_current_session(FALSE))
session |
The current Shiny session (if any). |
This function should generally only be called at print/render time. For example:
Inside the preRenderHook
of htmlwidgets::createWidget()
.
Inside of a custom print method that generates htmltools::tags.
Inside of a htmltools::tagFunction()
Calling this function at print/render time is important because it does different things based on the context in which it's called:
If a reactive context is active, session$getCurrentTheme()
is called
(which is a reactive read).
If no reactive context is active, shiny::getCurrentTheme()
is called
(which returns the current app's theme
, if relevant).
If shiny::getCurrentTheme()
comes up empty, then bs_global_get()
is called, which is relevant for rmarkdown::html_document()
, and
possibly other static rendering contexts.
Returns a bs_theme()
object.
Other Bootstrap theme functions:
bs_add_variables()
,
bs_dependency()
,
bs_global_theme()
,
bs_remove()
,
bs_theme()
,
bs_theme_dependencies()
,
bs_theme_preview()
Themeable HTML components use Sass to generate CSS rules from Bootstrap Sass
variables, functions, and/or mixins (i.e., stuff inside of theme
).
bs_dependencies()
makes it a bit easier to create themeable components by
compiling sass::sass()
(input
) together with Bootstrap Sass inside of a
theme
, and packaging up the result into an htmltools::htmlDependency()
.
Themable components can also be dynamically themed inside of Shiny (i.e.,
they may be themed in 'real-time' via bs_themer()
, and more generally,
update their styles in response to shiny::session's setCurrentTheme()
method). Dynamically themeable components provide a "recipe" (i.e., a
function) to bs_dependency_defer()
, describing how to generate new CSS
stylesheet(s) from a new theme
. This function is called when the HTML page
is first rendered, and may be invoked again with a new theme
whenever
shiny::session's setCurrentTheme()
is called.
bs_dependency( input = list(), theme, name, version, cache_key_extra = NULL, .dep_args = list(), .sass_args = list() ) bs_dependency_defer(func, memoise = TRUE)
bs_dependency( input = list(), theme, name, version, cache_key_extra = NULL, .dep_args = list(), .sass_args = list() ) bs_dependency_defer(func, memoise = TRUE)
input |
Sass rules to compile, using |
theme |
A |
name |
Library name |
version |
Library version |
cache_key_extra |
Extra information to add to the sass cache key. It is useful to add the version of your package. |
.dep_args |
A list of additional arguments to pass to
|
.sass_args |
A list of additional arguments to pass to
|
func |
a non-anonymous function, with a single argument.
This function should accept a |
memoise |
whether or not to memoise (i.e., cache) |
bs_dependency()
returns an htmltools::htmlDependency()
and
bs_dependency_defer()
returns an htmltools::tagFunction()
Theming: Custom components gives a tutorial on creating a dynamically themable custom component.
Other Bootstrap theme functions:
bs_add_variables()
,
bs_current_theme()
,
bs_global_theme()
,
bs_remove()
,
bs_theme()
,
bs_theme_dependencies()
,
bs_theme_preview()
myWidgetVersion <- "1.2.3" myWidgetDependency <- function() { list( bs_dependency_defer(myWidgetCss), htmlDependency( name = "mywidget-js", version = myWidgetVersion, src = system.file(package = "mypackage", "js"), script = "mywidget.js" ) ) } myWidgetCSS <- function(theme) { if (!is_bs_theme(theme)) { return( htmlDependency( name = "mywidget-css", version = myWidgetVersion, src = system.file(package = "mypackage", "css"), stylesheet = "mywidget.css" ) ) } # Compile mywidget.scss using the variables and defaults from the theme # object. sass_input <- sass::sass_file(system.file(package = "mypackage", "scss/mywidget.scss")) bs_dependency( input = sass_input, theme = theme, name = "mywidget", version = myWidgetVersion, cache_key_extra = utils::packageVersion("mypackage") ) } # Note that myWidgetDependency is not defined inside of myWidget. This is so # that, if `myWidget()` is called multiple times, Shiny can tell that the # function objects are identical and deduplicate them. myWidget <- function(id) { div( id = id, span("myWidget"), myWidgetDependency() ) }
myWidgetVersion <- "1.2.3" myWidgetDependency <- function() { list( bs_dependency_defer(myWidgetCss), htmlDependency( name = "mywidget-js", version = myWidgetVersion, src = system.file(package = "mypackage", "js"), script = "mywidget.js" ) ) } myWidgetCSS <- function(theme) { if (!is_bs_theme(theme)) { return( htmlDependency( name = "mywidget-css", version = myWidgetVersion, src = system.file(package = "mypackage", "css"), stylesheet = "mywidget.css" ) ) } # Compile mywidget.scss using the variables and defaults from the theme # object. sass_input <- sass::sass_file(system.file(package = "mypackage", "scss/mywidget.scss")) bs_dependency( input = sass_input, theme = theme, name = "mywidget", version = myWidgetVersion, cache_key_extra = utils::packageVersion("mypackage") ) } # Note that myWidgetDependency is not defined inside of myWidget. This is so # that, if `myWidget()` is called multiple times, Shiny can tell that the # function objects are identical and deduplicate them. myWidget <- function(id) { div( id = id, span("myWidget"), myWidgetDependency() ) }
Useful for retrieving a variable from the current theme and using the value to inform another R function.
bs_get_variables(theme, varnames) bs_get_contrast(theme, varnames)
bs_get_variables(theme, varnames) bs_get_contrast(theme, varnames)
theme |
A |
varnames |
A character string referencing a Sass variable in the current theme. |
Returns a character string containing a CSS/Sass value. If the
variable(s) are not defined, their value is NA
.
Theming: Bootstrap 5 variables provides a searchable reference of all theming variables available in Bootstrap 5.
Other Bootstrap theme utility functions:
bootswatch_themes()
,
builtin_themes()
,
theme_bootswatch()
,
theme_version()
,
versions()
vars <- c("body-bg", "body-color", "primary", "border-radius") bs_get_variables(bs_theme(), varnames = vars) bs_get_variables(bs_theme(bootswatch = "darkly"), varnames = vars) bs_get_contrast(bs_theme(), c("primary", "dark", "light")) library(htmltools) div( class = "bg-primary", style = css( color = bs_get_contrast(bs_theme(), "primary") ) )
vars <- c("body-bg", "body-color", "primary", "border-radius") bs_get_variables(bs_theme(), varnames = vars) bs_get_variables(bs_theme(bootswatch = "darkly"), varnames = vars) bs_get_contrast(bs_theme(), c("primary", "dark", "light")) library(htmltools) div( class = "bg-primary", style = css( color = bs_get_contrast(bs_theme(), "primary") ) )
bs_global_theme()
creates and sets the global Bootstrap Sass theme. This
theme is typically found by bs_theme_dependencies()
in the app or document
where the global theme is being used. You can obtain the current global theme
with bs_global_get()
or directly set the global theme with
bs_global_set()
.
bs_global_theme( version = version_default(), preset = NULL, bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, ..., bootswatch = NULL ) bs_global_set(theme = bs_theme()) bs_global_get() bs_global_clear() bs_global_add_variables( ..., .where = "defaults", .default_flag = identical(.where, "defaults") ) bs_global_add_rules(...) bs_global_bundle(...) bs_global_theme_update( ..., preset = NULL, bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, bootswatch = NULL )
bs_global_theme( version = version_default(), preset = NULL, bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, ..., bootswatch = NULL ) bs_global_set(theme = bs_theme()) bs_global_get() bs_global_clear() bs_global_add_variables( ..., .where = "defaults", .default_flag = identical(.where, "defaults") ) bs_global_add_rules(...) bs_global_bundle(...) bs_global_theme_update( ..., preset = NULL, bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, bootswatch = NULL )
version |
The major version of Bootstrap to use (see |
preset |
The name of a theme preset, either a built-in theme provided by
bslib or a Bootswatch theme (see |
bg |
A color string for the background. |
fg |
A color string for the foreground. |
primary |
A color to be used for hyperlinks, to indicate primary/default actions, and to show active selection state in some Bootstrap components. Generally a bold, saturated color that contrasts with the theme's base colors. |
secondary |
A color for components and messages that don't need to stand out. (Not supported in Bootstrap 3.) |
success |
A color for messages that indicate an operation has succeeded. Typically green. |
info |
A color for messages that are informative but not critical. Typically a shade of blue-green. |
warning |
A color for warning messages. Typically yellow. |
danger |
A color for errors. Typically red. |
base_font |
The default typeface. |
code_font |
The typeface to be used for code. Be sure this is monospace! |
heading_font |
The typeface to be used for heading elements. |
... |
arguments passed along to |
bootswatch |
The name of a bootswatch theme (see |
theme |
A |
.where |
Whether to place the variable definitions before other Sass
|
.default_flag |
Whether or not to add a |
Functions that modify the global theme (e.g., bs_global_set()
)
invisibly return the previously set theme. bs_global_get()
returns the
current global theme.
Other Bootstrap theme functions:
bs_add_variables()
,
bs_current_theme()
,
bs_dependency()
,
bs_remove()
,
bs_theme()
,
bs_theme_dependencies()
,
bs_theme_preview()
# Remember the global state now (so we can restore later) theme <- bs_global_get() # Use Bootstrap 3 (globally) with some theme customization bs_global_theme(3, bg = "#444", fg = "#e4e4e4", primary = "#e39777") if (rlang::is_interactive()) { bs_theme_preview(with_themer = FALSE) } # If no global theme is active, bs_global_get() returns NULL bs_global_clear() bs_global_get() # Restore the original state bs_global_set(theme)
# Remember the global state now (so we can restore later) theme <- bs_global_get() # Use Bootstrap 3 (globally) with some theme customization bs_global_theme(3, bg = "#444", fg = "#e4e4e4", primary = "#e39777") if (rlang::is_interactive()) { bs_theme_preview(with_themer = FALSE) } # If no global theme is active, bs_global_get() returns NULL bs_global_clear() bs_global_get() # Restore the original state bs_global_set(theme)
A Bootstrap theme created with bs_theme()
is comprised of
many Sass layers.
bs_remove()
and bs_retrieve()
allow you to remove or retrieve an
individual layer, either to reduce the size of the compiled CSS or to extract
styles from a theme.
bs_remove(theme, ids = character(0)) bs_retrieve(theme, ids = character(0), include_unnamed = TRUE)
bs_remove(theme, ids = character(0)) bs_retrieve(theme, ids = character(0), include_unnamed = TRUE)
theme |
A |
ids |
a character vector of ids |
include_unnamed |
whether or not to include unnamed |
Returns a modified bs_theme()
object.
Other Bootstrap theme functions:
bs_add_variables()
,
bs_current_theme()
,
bs_dependency()
,
bs_global_theme()
,
bs_theme()
,
bs_theme_dependencies()
,
bs_theme_preview()
bs4 <- bs_theme(version = 4) # Retrieve sass bundle for print styles bs_retrieve(bs4, "_print", include_unnamed = FALSE) # Remove CSS rules for print and carousels bs4_no_print <- bs_remove(bs4, c("_print", "_carousel")) suppressWarnings( bs_retrieve(bs4_no_print, "_print", include_unnamed = FALSE) ) # Remove BS3 compatibility layer bs4_no_compat <- bs_remove(bs4, "bs3compat")
bs4 <- bs_theme(version = 4) # Retrieve sass bundle for print styles bs_retrieve(bs4, "_print", include_unnamed = FALSE) # Remove CSS rules for print and carousels bs4_no_print <- bs_remove(bs4, c("_print", "_carousel")) suppressWarnings( bs_retrieve(bs4_no_print, "_print", include_unnamed = FALSE) ) # Remove BS3 compatibility layer bs4_no_compat <- bs_remove(bs4, "bs3compat")
Creates a Bootstrap theme object, where you can:
Choose a (major) Bootstrap version
.
Choose a Bootswatch theme (optional).
Customize main colors and fonts via explicitly named arguments (e.g.,
bg
, fg
, primary
, etc).
Customize other, lower-level, Bootstrap Sass variable defaults via ...
.
To learn more about how to implement custom themes, as well as how to use them inside Shiny and R Markdown, see here.
bs_theme( version = version_default(), preset = NULL, ..., bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, font_scale = NULL, bootswatch = NULL ) bs_theme_update( theme, ..., preset = NULL, bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, font_scale = NULL, bootswatch = NULL ) is_bs_theme(x)
bs_theme( version = version_default(), preset = NULL, ..., bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, font_scale = NULL, bootswatch = NULL ) bs_theme_update( theme, ..., preset = NULL, bg = NULL, fg = NULL, primary = NULL, secondary = NULL, success = NULL, info = NULL, warning = NULL, danger = NULL, base_font = NULL, code_font = NULL, heading_font = NULL, font_scale = NULL, bootswatch = NULL ) is_bs_theme(x)
version |
The major version of Bootstrap to use (see |
preset |
The name of a theme preset, either a built-in theme provided by
bslib or a Bootswatch theme (see |
... |
arguments passed along to |
bg |
A color string for the background. |
fg |
A color string for the foreground. |
primary |
A color to be used for hyperlinks, to indicate primary/default actions, and to show active selection state in some Bootstrap components. Generally a bold, saturated color that contrasts with the theme's base colors. |
secondary |
A color for components and messages that don't need to stand out. (Not supported in Bootstrap 3.) |
success |
A color for messages that indicate an operation has succeeded. Typically green. |
info |
A color for messages that are informative but not critical. Typically a shade of blue-green. |
warning |
A color for warning messages. Typically yellow. |
danger |
A color for errors. Typically red. |
base_font |
The default typeface. |
code_font |
The typeface to be used for code. Be sure this is monospace! |
heading_font |
The typeface to be used for heading elements. |
font_scale |
A scalar multiplier to apply to the base font size. For
example, a value of |
bootswatch |
The name of a bootswatch theme (see |
theme |
A |
x |
an object. |
Returns a sass::sass_bundle()
(list-like) object.
Colors may be provided in any format that htmltools::parseCssColors()
can
understand. To control the vast majority of the ('grayscale') color
defaults, specify both the fg
(foreground) and bg
(background) colors.
The primary
and secondary
theme colors are also useful for accenting the
main grayscale colors in things like hyperlinks, tabset panels, and buttons.
Use base_font
, code_font
, and heading_font
to control the main
typefaces. These arguments set new defaults for the relevant font-family
CSS properties, but don't necessarily import the relevant font files. To
both set CSS properties and import font files, consider using the various
font_face()
helpers.
Each *_font
argument may be a single font or a font_collection()
.
A font can be created with font_google()
, font_link()
, or font_face()
,
or it can be a character vector of font names in the following format:
A single unquoted name (e.g., "Source Sans Pro"
).
A single quoted name (e.g., "'Source Sans Pro'"
).
A comma-separated list of names w/ individual names quoted as necessary.
(e.g. c("Open Sans", "'Source Sans Pro'", "'Helvetica Neue', Helvetica, sans-serif")
)
font_google()
sets local = TRUE
by default, which ensures that the font
files are downloaded from Google Fonts when
your document or app is rendered. This guarantees that the client has access
to the font family, making it relatively safe to specify just one font
family:
bs_theme(base_font = font_google("Pacifico", local = TRUE))
That said, we recommend you specify multiple "fallback" font families, especially when relying on remote and/or system fonts being available. Fallback fonts are useful not only for handling missing fonts, but also ensure that your users don't experience a Flash of Invisible Text (FOIT) which can be quite noticeable with remote web fonts on a slow internet connection.
bs_theme(base_font = font_collection(font_google("Pacifico", local = FALSE), "Roboto", "sans-serif"))
Get Started: Theming introduces theming with bslib in Shiny apps and R Markdown documents.
Theming: Bootstrap 5 variables provides a searchable reference of all theming variables available in Bootstrap 5.
Theming: Custom components gives a tutorial on creating a dynamically themable custom component.
bslib's theming capabilities are powered by the sass package.
Bootstrap's utility classes
can be helpful when you want to change the appearance of an element
without writing CSS or customizing your bs_theme()
.
Other Bootstrap theme functions:
bs_add_variables()
,
bs_current_theme()
,
bs_dependency()
,
bs_global_theme()
,
bs_remove()
,
bs_theme_dependencies()
,
bs_theme_preview()
theme <- bs_theme( # Controls the default grayscale palette bg = "#202123", fg = "#B8BCC2", # Controls the accent (e.g., hyperlink, button, etc) colors primary = "#EA80FC", secondary = "#48DAC6", base_font = c("Grandstander", "sans-serif"), code_font = c("Courier", "monospace"), heading_font = "'Helvetica Neue', Helvetica, sans-serif", # Can also add lower-level customization "input-border-color" = "#EA80FC" ) bs_theme_preview(theme) # Lower-level bs_add_*() functions allow you to work more # directly with the underlying Sass code theme <- bs_add_variables(theme, "my-class-color" = "red") theme <- bs_add_rules(theme, ".my-class { color: $my-class-color }")
theme <- bs_theme( # Controls the default grayscale palette bg = "#202123", fg = "#B8BCC2", # Controls the accent (e.g., hyperlink, button, etc) colors primary = "#EA80FC", secondary = "#48DAC6", base_font = c("Grandstander", "sans-serif"), code_font = c("Courier", "monospace"), heading_font = "'Helvetica Neue', Helvetica, sans-serif", # Can also add lower-level customization "input-border-color" = "#EA80FC" ) bs_theme_preview(theme) # Lower-level bs_add_*() functions allow you to work more # directly with the underlying Sass code theme <- bs_add_variables(theme, "my-class-color" = "red") theme <- bs_add_rules(theme, ".my-class { color: $my-class-color }")
bs_theme_dependencies()
compiles Bootstrap Sass into CSS and returns it,
along with other HTML dependencies, as a list of
htmltools::htmlDependency()
s. Most users won't need to call this function
directly as Shiny & R Markdown will perform this compilation automatically
when handed a bs_theme()
. If you're here looking to create a themeable
component, see bs_dependency()
.
bs_theme_dependencies( theme, sass_options = sass::sass_options_get(output_style = "compressed"), cache = sass::sass_cache_get(), jquery = jquerylib::jquery_core(3), precompiled = get_precompiled_option("bslib.precompiled", default = TRUE) )
bs_theme_dependencies( theme, sass_options = sass::sass_options_get(output_style = "compressed"), cache = sass::sass_cache_get(), jquery = jquerylib::jquery_core(3), precompiled = get_precompiled_option("bslib.precompiled", default = TRUE) )
theme |
A |
sass_options |
a |
cache |
This can be a directory to use for the cache, a FileCache
object created by |
jquery |
a |
precompiled |
Before compiling the theme object, first look for a
precompiled CSS file for the |
Returns a list of HTML dependencies containing Bootstrap CSS,
Bootstrap JavaScript, and jquery
. This list may contain additional HTML
dependencies if bundled with the theme
.
If Shiny Developer Mode is enabled (by setting options(shiny.devmode = TRUE)
or calling shiny::devmode(TRUE)
), both sass caching and
bslib precompilation are disabled by default; that is, a call to
bs_theme_dependencies(theme)
expands to bs_theme_dependencies(theme, cache = F, precompiled = F)
). This is useful for local development as enabling
caching/precompilation may produce incorrect results if local changes are
made to bslib's source files.
Other Bootstrap theme functions:
bs_add_variables()
,
bs_current_theme()
,
bs_dependency()
,
bs_global_theme()
,
bs_remove()
,
bs_theme()
,
bs_theme_preview()
# Function to preview the styling a (primary) Bootstrap button library(htmltools) button <- tags$a(class = "btn btn-primary", href = "#", role = "button", "Hello") preview_button <- function(theme) { browsable(tags$body(bs_theme_dependencies(theme), button)) } # Latest Bootstrap preview_button(bs_theme()) # Bootstrap 3 preview_button(bs_theme(3)) # Bootswatch 4 minty theme preview_button(bs_theme(4, bootswatch = "minty")) # Bootswatch 4 sketchy theme preview_button(bs_theme(4, bootswatch = "sketchy"))
# Function to preview the styling a (primary) Bootstrap button library(htmltools) button <- tags$a(class = "btn btn-primary", href = "#", role = "button", "Hello") preview_button <- function(theme) { browsable(tags$body(bs_theme_dependencies(theme), button)) } # Latest Bootstrap preview_button(bs_theme()) # Bootstrap 3 preview_button(bs_theme(3)) # Bootswatch 4 minty theme preview_button(bs_theme(4, bootswatch = "minty")) # Bootswatch 4 sketchy theme preview_button(bs_theme(4, bootswatch = "sketchy"))
Launches an example shiny app that can be used to get a quick preview of a
bs_theme()
, as well as an interactive GUI for tweaking some of the
main theme settings. Calling bs_theme_preview()
with no arguments starts
the theme preview app with the default theme, which is a great way to see
the available theme presets or to start creating your own theme.
bs_theme_preview(theme = bs_theme(), ..., with_themer = TRUE)
bs_theme_preview(theme = bs_theme(), ..., with_themer = TRUE)
theme |
A |
... |
passed along to |
with_themer |
whether or not to run the app with |
The app that this launches is subject to change as new features are developed in bslib and shiny.
nothing, this function is called for its side-effects (launching an application).
Use run_with_themer()
or bs_themer()
to add the theming UI to
an existing shiny app.
Other Bootstrap theme functions:
bs_add_variables()
,
bs_current_theme()
,
bs_dependency()
,
bs_global_theme()
,
bs_remove()
,
bs_theme()
,
bs_theme_dependencies()
theme <- bs_theme(bg = "#6c757d", fg = "white", primary = "orange") bs_theme_preview(theme)
theme <- bs_theme(bg = "#6c757d", fg = "white", primary = "orange") bs_theme_preview(theme)
Obtain a list of all available built-in bslib themes.
builtin_themes(version = version_default(), full_path = FALSE)
builtin_themes(version = version_default(), full_path = FALSE)
version |
the major version of Bootstrap. |
full_path |
whether to return a path to the installed theme. |
Returns a character vector of built-in themes provided by bslib.
Other Bootstrap theme utility functions:
bootswatch_themes()
,
bs_get_variables()
,
theme_bootswatch()
,
theme_version()
,
versions()
A general purpose container for grouping related UI elements together with a
border and optional padding. To learn more about card()
s, see the Cards article or the
other articles listed in the References section below.
card( ..., full_screen = FALSE, height = NULL, max_height = NULL, min_height = NULL, fill = TRUE, class = NULL, wrapper = card_body, id = NULL )
card( ..., full_screen = FALSE, height = NULL, max_height = NULL, min_height = NULL, fill = TRUE, class = NULL, wrapper = card_body, id = NULL )
... |
Unnamed arguments can be any valid child of an htmltools tag (which includes card items such as |
full_screen |
If |
height |
Any valid CSS unit (e.g.,
|
max_height , min_height
|
Any valid CSS unit (e.g.,
|
fill |
Whether or not to allow the card to grow/shrink to fit a
fillable container with an opinionated height (e.g., |
class |
Additional CSS classes for the returned UI element. |
wrapper |
A function (which returns a UI element) to call on unnamed
arguments in |
id |
Provide a unique identifier for the |
A htmltools::div()
tag.
Several articles on the bslib website feature the card component:
Card item functions create the various parts of a card.
navset_card_tab()
, navset_card_pill()
and
navset_card_underline()
create cards with tabbed navigation.
layout_columns()
and layout_column_wrap()
help position multiple
cards into columns and rows and can also be used inside a card.
layout_sidebar()
adds a sidebar to a card when nested in card()
or card_body()
.
value_box()
uses card()
to highlight a showcase a key piece of
information.
Other Components:
accordion()
,
popover()
,
tooltip()
,
value_box()
library(htmltools) card( full_screen = TRUE, card_header( "This is the header" ), card_body( p("This is the body."), p("This is still the body.") ), card_footer( "This is the footer" ) )
library(htmltools) card( full_screen = TRUE, card_header( "This is the header" ), card_body( p("This is the body."), p("This is still the body.") ), card_footer( "This is the footer" ) )
Components designed to be provided as direct children of a card()
. For a
general overview of the card()
API, see the Cards article or the
other articles listed in the References section of the card()
documentation.
card_body( ..., fillable = TRUE, min_height = NULL, max_height = NULL, max_height_full_screen = max_height, height = NULL, padding = NULL, gap = NULL, fill = TRUE, class = NULL ) card_title(..., container = htmltools::h5) card_header(..., class = NULL, container = htmltools::div) card_footer(..., class = NULL) card_image( file, ..., alt = "", src = NULL, href = NULL, border_radius = c("auto", "top", "bottom", "all", "none"), mime_type = NULL, class = NULL, height = NULL, fill = FALSE, width = NULL, container = NULL ) as.card_item(x) is.card_item(x)
card_body( ..., fillable = TRUE, min_height = NULL, max_height = NULL, max_height_full_screen = max_height, height = NULL, padding = NULL, gap = NULL, fill = TRUE, class = NULL ) card_title(..., container = htmltools::h5) card_header(..., class = NULL, container = htmltools::div) card_footer(..., class = NULL) card_image( file, ..., alt = "", src = NULL, href = NULL, border_radius = c("auto", "top", "bottom", "all", "none"), mime_type = NULL, class = NULL, height = NULL, fill = FALSE, width = NULL, container = NULL ) as.card_item(x) is.card_item(x)
... |
Unnamed arguments can be any valid child of an htmltools tag. Named arguments become HTML attributes on returned UI element. |
fillable |
Whether or not the card item should be a fillable (i.e. flexbox) container. |
min_height , max_height , max_height_full_screen
|
Any valid CSS length unit. |
height |
Any valid CSS unit (e.g.,
|
padding |
Padding to use for the body. This can be a numeric vector (which will be interpreted as pixels) or a character vector with valid CSS lengths. The length can be between one and four. If one, then that value will be used for all four sides. If two, then the first value will be used for the top and bottom, while the second value will be used for left and right. If three, then the first will be used for top, the second will be left and right, and the third will be bottom. If four, then the values will be interpreted as top, right, bottom, and left respectively. |
gap |
A CSS length unit defining the
|
fill |
Whether to allow this element to grow/shrink to fit its |
class |
Additional CSS classes for the returned UI element. |
container |
A function to generate an HTML element to contain the image.
Setting this value to |
file |
A file path pointing an image. Local images (i.e. not a URI
starting with |
alt |
Alternate text for the image, used by screen readers and assistive devices. Provide alt text with a description of the image for any images with important content. If alt text is not provided, the image will be considered to be decorative and will not be read or announced by screen readers. For more information, the Web Accessibility Initiative (WAI) has a helpful tutorial on alt text. |
src |
The |
href |
An optional URL to link to when a user clicks on the image. |
border_radius |
Which side of the image should have rounded corners,
useful when The value of |
mime_type |
The mime type of the |
width |
Any valid CSS unit (e.g.,
|
x |
an object to test (or coerce to) a card item. |
An htmltools::div()
tag.
card_body()
: A general container for the "main content" of a card()
.
card_title()
: Similar to card_header()
but without the border and background color.
card_header()
: A header (with border and background color) for the card()
. Typically appears before a card_body()
.
card_footer()
: A header (with border and background color) for the card()
. Typically appears after a card_body()
.
card_image()
: Include static images in a card, for example as an
image cap at the top or bottom of the card.
as.card_item()
: Mark an object as a card item. This will prevent the
card()
from putting the object inside a wrapper
(i.e., a
card_body()
).
card()
creates a card component.
navset_card_tab()
, navset_card_pill()
and
navset_card_underline()
create cards with tabbed navigation.
layout_columns()
and layout_column_wrap()
help position multiple
cards into columns and rows and can also be used inside a card.
layout_sidebar()
adds a sidebar to a card when nested in card()
or card_body()
.
font_google()
, font_link()
, and font_face()
are all re-exported from
the sass package (see sass::font_face()
for details). For a quick
example of how to use these functions with bs_theme()
, see the
examples section below.
# If you have an internet connection, running the following code # will download, cache, and import the relevant Google Font files # for local use theme <- bs_theme( base_font = font_google("Fira Sans"), code_font = font_google("Fira Code"), heading_font = font_google("Fredoka One") ) if (interactive()) { bs_theme_preview(theme) } # Three different yet equivalent ways of importing a remotely-hosted Google Font a <- font_google("Crimson Pro", wght = "200..900", local = FALSE) b <- font_link( "Crimson Pro", href = "https://fonts.googleapis.com/css2?family=Crimson+Pro:[email protected]" ) url <- "https://fonts.gstatic.com/s/crimsonpro/v13/q5uDsoa5M_tv7IihmnkabARboYF6CsKj.woff2" c <- font_face( family = "Crimson Pro", style = "normal", weight = "200 900", src = paste0("url(", url, ") format('woff2')") ) theme <- bs_theme(base_font = c) if (interactive()) { bs_theme_preview(theme) }
# If you have an internet connection, running the following code # will download, cache, and import the relevant Google Font files # for local use theme <- bs_theme( base_font = font_google("Fira Sans"), code_font = font_google("Fira Code"), heading_font = font_google("Fredoka One") ) if (interactive()) { bs_theme_preview(theme) } # Three different yet equivalent ways of importing a remotely-hosted Google Font a <- font_google("Crimson Pro", wght = "200..900", local = FALSE) b <- font_link( "Crimson Pro", href = "https://fonts.googleapis.com/css2?family=Crimson+Pro:[email protected]" ) url <- "https://fonts.gstatic.com/s/crimsonpro/v13/q5uDsoa5M_tv7IihmnkabARboYF6CsKj.woff2" c <- font_face( family = "Crimson Pro", style = "normal", weight = "200 900", src = paste0("url(", url, ") format('woff2')") ) theme <- bs_theme(base_font = c) if (interactive()) { bs_theme_preview(theme) }
Creates a button that toggles between dark and light modes, specifically for toggling between light and dark Bootstrap color modes – a new feature added in Bootstrap 5.3.
input_dark_mode(..., id = NULL, mode = NULL) toggle_dark_mode(mode = NULL, ..., session = get_current_session())
input_dark_mode(..., id = NULL, mode = NULL) toggle_dark_mode(mode = NULL, ..., session = get_current_session())
... |
Additional attributes to be passed to the input control UI, such
as In |
id |
An optional input id, required to reactively read the current color mode. |
mode |
The initial mode of the dark mode switch. By default or when set
to |
session |
A Shiny session object (the default should almost always be used). |
Returns a UI element for a dark mode switch input control. The server
value received for the input corresponding to id
will be a string value
with the current color mode ("light"
or "dark"
).
input_dark_mode()
: Create a dark mode switch input control
toggle_dark_mode()
: Programmatically toggle or set the current light
or dark color mode.
Other input controls:
input_switch()
Create an on-off style switch control for specifying logical values.
input_switch(id, label, value = FALSE, width = NULL) update_switch(id, label = NULL, value = NULL, session = get_current_session()) toggle_switch(id, value = NULL, session = get_current_session())
input_switch(id, label, value = FALSE, width = NULL) update_switch(id, label = NULL, value = NULL, session = get_current_session()) toggle_switch(id, value = NULL, session = get_current_session())
id |
An input id. |
label |
A label for the switch. |
value |
Whether or not the switch should be checked by default. |
width |
Any valid CSS unit (e.g.,
|
session |
a shiny session object (the default should almost always be used). |
Returns a UI element for a switch input control. The server value
received for the input corresponding to id
will be a logical
(TRUE
/FALSE
) value.
Other input controls:
input_dark_mode()
library(shiny) library(bslib) ui <- page_fixed( title = "Keyboard Settings", h2("Keyboard Settings"), input_switch("auto_capitalization", "Auto-Capitalization", TRUE), input_switch("auto_correction", "Auto-Correction", TRUE), input_switch("check_spelling", "Check Spelling", TRUE), input_switch("smart_punctuation", "Smart Punctuation"), h2("Preview"), verbatimTextOutput("preview") ) server <- function(input, output, session) { output$preview <- renderPrint({ list( auto_capitalization = input$auto_capitalization, auto_correction = input$auto_correction, check_spelling = input$check_spelling, smart_punctuation = input$smart_punctuation ) }) } shinyApp(ui, server)
library(shiny) library(bslib) ui <- page_fixed( title = "Keyboard Settings", h2("Keyboard Settings"), input_switch("auto_capitalization", "Auto-Capitalization", TRUE), input_switch("auto_correction", "Auto-Correction", TRUE), input_switch("check_spelling", "Check Spelling", TRUE), input_switch("smart_punctuation", "Smart Punctuation"), h2("Preview"), verbatimTextOutput("preview") ) server <- function(input, output, session) { output$preview <- renderPrint({ list( auto_capitalization = input$auto_capitalization, auto_correction = input$auto_correction, check_spelling = input$check_spelling, smart_punctuation = input$smart_punctuation ) }) } shinyApp(ui, server)
input_task_button
is a button that can be used in conjuction with
shiny::bindEvent()
(or the older shiny::eventReactive()
and
shiny::observeEvent()
functions) to trigger actions or recomputation.
It is similar to shiny::actionButton()
, except it prevents the user from
clicking when its operation is already in progress.
Upon click, it automatically displays a customizable progress message and disables itself; and after the server has dealt with whatever reactivity is triggered from the click, the button automatically reverts to its original appearance and re-enables itself.
input_task_button( id, label, ..., icon = NULL, label_busy = "Processing...", icon_busy = rlang::missing_arg(), type = "primary", auto_reset = TRUE ) update_task_button(id, ..., state = NULL, session = get_current_session())
input_task_button( id, label, ..., icon = NULL, label_busy = "Processing...", icon_busy = rlang::missing_arg(), type = "primary", auto_reset = TRUE ) update_task_button(id, ..., state = NULL, session = get_current_session())
id |
The |
label |
The label of the button while it is in ready (clickable) state; usually a string. |
... |
Named arguments become attributes to include on the |
icon |
An optional icon to display next to the label while the button is
in ready state. See |
label_busy |
The label of the button while it is busy. |
icon_busy |
The icon to display while the button is busy. By default,
|
type |
One of the Bootstrap theme colors ( |
auto_reset |
If |
state |
If |
session |
The |
In some advanced use cases, it may be necessary to keep a task button in its
busy state even after the normal reactive processing has completed. Calling
update_task_button(id, state = "busy")
from the server will opt out of any
currently pending reset for a specific task button. After doing so, the
button can be re-enabled by calling update_task_button(id, state = "ready")
after each click's work is complete.
You can also pass an explicit auto_reset = FALSE
to input_task_button()
,
which means that button will never be automatically re-enabled and will
require update_task_button(id, state = "ready")
to be called each time.
Note that, as a general rule, Shiny's update
family of functions do not
take effect at the instant that they are called, but are held until the end
of the current reactive cycle. So if you have many different reactive
calculations and outputs, you don't have to be too careful about when you
call update_task_button(id, state = "ready")
, as the button on the client
will not actually re-enable until the same moment that all of the updated
outputs simultaneously sent to the client.
An integer of class "shinyActionButtonValue"
. This class differs from
ordinary integers in that a value of 0 is considered "falsy".
This implies two things:
Event handlers (e.g., shiny::observeEvent()
, shiny::eventReactive()
) won't execute on initial load.
Input validation (e.g., shiny::req()
, shiny::need()
) will fail on initial load.
library(shiny) library(bslib) ui <- page_sidebar( sidebar = sidebar( open = "always", input_task_button("resample", "Resample"), ), verbatimTextOutput("summary") ) server <- function(input, output, session) { sample <- eventReactive(input$resample, ignoreNULL=FALSE, { Sys.sleep(2) # Make this artificially slow rnorm(100) }) output$summary <- renderPrint({ summary(sample()) }) } shinyApp(ui, server)
library(shiny) library(bslib) ui <- page_sidebar( sidebar = sidebar( open = "always", input_task_button("resample", "Resample"), ), verbatimTextOutput("summary") ) server <- function(input, output, session) { sample <- eventReactive(input$resample, ignoreNULL=FALSE, { Sys.sleep(2) # Make this artificially slow rnorm(100) }) output$summary <- renderPrint({ summary(sample()) }) } shinyApp(ui, server)
Wraps a 1d sequence of UI elements into a 2d grid. The number of columns (and
rows) in the grid dependent on the column width
as well as the size of the
display. For more explanation and illustrative examples, see the References
section below.
layout_column_wrap( ..., width = "200px", fixed_width = FALSE, heights_equal = c("all", "row"), fill = TRUE, fillable = TRUE, height = NULL, height_mobile = NULL, min_height = NULL, max_height = NULL, gap = NULL, class = NULL )
layout_column_wrap( ..., width = "200px", fixed_width = FALSE, heights_equal = c("all", "row"), fill = TRUE, fillable = TRUE, height = NULL, height_mobile = NULL, min_height = NULL, max_height = NULL, gap = NULL, class = NULL )
... |
Unnamed arguments should be UI elements (e.g., |
width |
The desired width of each card, which can be any of the following:
|
fixed_width |
When |
heights_equal |
If |
fill |
Whether or not to allow the layout to grow/shrink to fit a
fillable container with an opinionated height (e.g., |
fillable |
Whether or not each element is wrapped in a fillable container. |
height |
Any valid CSS unit (e.g.,
|
height_mobile |
Any valid CSS unit to use for the height when on mobile devices (or narrow windows). |
min_height , max_height
|
The maximum or minimum height of the layout container.
Can be any valid CSS unit (e.g.,
|
gap |
A CSS length unit defining the
|
class |
Additional CSS classes for the returned UI element. |
The bslib website features layout_column_wrap()
in two places:
Other Column layouts:
layout_columns()
x <- card("A simple card") # Always has 2 columns (on non-mobile) layout_column_wrap(width = 1/2, x, x, x) # Automatically lays out three cards into columns # such that each column is at least 200px wide: layout_column_wrap(x, x, x) # To use larger column widths by default, set `width`. # This example has 3 columns when the screen is at least 900px wide: layout_column_wrap(width = "300px", x, x, x) # You can add a list of items, spliced with rlang's `!!!` operator layout_column_wrap(!!!list(x, x, x))
x <- card("A simple card") # Always has 2 columns (on non-mobile) layout_column_wrap(width = 1/2, x, x, x) # Automatically lays out three cards into columns # such that each column is at least 200px wide: layout_column_wrap(x, x, x) # To use larger column widths by default, set `width`. # This example has 3 columns when the screen is at least 900px wide: layout_column_wrap(width = "300px", x, x, x) # You can add a list of items, spliced with rlang's `!!!` operator layout_column_wrap(!!!list(x, x, x))
Create responsive, column-based grid layouts, based on a 12-column grid.
layout_columns( ..., col_widths = NA, row_heights = NULL, fill = TRUE, fillable = TRUE, gap = NULL, class = NULL, height = NULL, min_height = NULL, max_height = NULL )
layout_columns( ..., col_widths = NA, row_heights = NULL, fill = TRUE, fillable = TRUE, gap = NULL, class = NULL, height = NULL, min_height = NULL, max_height = NULL )
... |
Unnamed arguments should be UI elements (e.g., |
col_widths |
One of the following:
|
row_heights |
One of the following:
|
fill |
Whether or not to allow the layout to grow/shrink to fit a
fillable container with an opinionated height (e.g., |
fillable |
Whether or not each element is wrapped in a fillable container. |
gap |
A CSS length unit defining the
|
class |
Additional CSS classes for the returned UI element. |
height |
Any valid CSS unit (e.g.,
|
min_height , max_height
|
The maximum or minimum height of the layout container.
Can be any valid CSS unit (e.g.,
|
Column-based layouts on the bslib website.
breakpoints()
for more information on specifying column widths at
responsive breakpoints.
Other Column layouts:
layout_column_wrap()
x <- card("A simple card") page_fillable( layout_columns(x, x, x, x) ) # Or add a list of items, spliced with rlang's `!!!` operator page_fillable( layout_columns(!!!list(x, x, x)) ) page_fillable( layout_columns( col_widths = c(6, 6, 12), x, x, x ) ) page_fillable( layout_columns( col_widths = c(6, 6, -2, 8), row_heights = c(1, 3), x, x, x ) ) page_fillable( fillable_mobile = TRUE, layout_columns( col_widths = breakpoints( sm = c(12, 12, 12), md = c(6, 6, 12), lg = c(4, 4, 4) ), x, x, x ) )
x <- card("A simple card") page_fillable( layout_columns(x, x, x, x) ) # Or add a list of items, spliced with rlang's `!!!` operator page_fillable( layout_columns(!!!list(x, x, x)) ) page_fillable( layout_columns( col_widths = c(6, 6, 12), x, x, x ) ) page_fillable( layout_columns( col_widths = c(6, 6, -2, 8), row_heights = c(1, 3), x, x, x ) ) page_fillable( fillable_mobile = TRUE, layout_columns( col_widths = breakpoints( sm = c(12, 12, 12), md = c(6, 6, 12), lg = c(4, 4, 4) ), x, x, x ) )
These functions are small wrappers around shiny's page constructors (i.e.,
shiny::fluidPage()
, shiny::navbarPage()
, etc) that differ in two ways:
The theme
parameter defaults bslib's recommended version of Bootstrap (for new projects).
The return value is rendered as an static HTML page when printed interactively at the console.
page(..., title = NULL, theme = bs_theme(), lang = NULL) page_fluid(..., title = NULL, theme = bs_theme(), lang = NULL) page_fixed(..., title = NULL, theme = bs_theme(), lang = NULL)
page(..., title = NULL, theme = bs_theme(), lang = NULL) page_fluid(..., title = NULL, theme = bs_theme(), lang = NULL) page_fixed(..., title = NULL, theme = bs_theme(), lang = NULL)
... |
UI elements for the page. Named arguments become HTML attributes. |
title |
The browser window title (defaults to the host URL of the page) |
theme |
A |
lang |
ISO 639-1 language code for the HTML page, such as "en" or "ko".
This will be used as the lang in the |
page()
: A bslib wrapper for shiny::bootstrapPage()
, a basic
Boostrap page where the content is added directly to the page body.
page_fluid()
: A bslib wrapper for shiny::fluidPage()
, a fluid
Bootstrap-based page layout that extends to the full viewport width.
page_fixed()
: A bslib wrapper for shiny::fixedPage()
, a fixed
Bootstrap-based page layout where the page content container is centered
horizontally and its width is constrained.
Dashboard-style pages: page_sidebar()
, page_navbar()
,
page_fillable()
.
A Bootstrap-based page layout whose contents fill the full height and width of the browser window.
page_fillable( ..., padding = NULL, gap = NULL, fillable_mobile = FALSE, title = NULL, theme = bs_theme(), lang = NULL )
page_fillable( ..., padding = NULL, gap = NULL, fillable_mobile = FALSE, title = NULL, theme = bs_theme(), lang = NULL )
... |
UI elements for the page. Named arguments become HTML attributes. |
padding |
Padding to use for the body. This can be a numeric vector (which will be interpreted as pixels) or a character vector with valid CSS lengths. The length can be between one and four. If one, then that value will be used for all four sides. If two, then the first value will be used for the top and bottom, while the second value will be used for left and right. If three, then the first will be used for top, the second will be left and right, and the third will be bottom. If four, then the values will be interpreted as top, right, bottom, and left respectively. |
gap |
A CSS length unit defining the
|
fillable_mobile |
Whether or not the page should fill the viewport's height on mobile devices (i.e., narrow windows). |
title |
The browser window title (defaults to the host URL of the page) |
theme |
A |
lang |
ISO 639-1 language code for the HTML page, such as "en" or "ko".
This will be used as the lang in the |
Filling Layouts on the bslib website.
Getting Started with Dashboards on the bslib website.
layout_columns()
and layout_column_wrap()
for laying out content
into rows and columns.
layout_sidebar()
for 'floating' sidebar layouts.
accordion()
for grouping related input controls in the sidebar
.
card()
for wrapping outputs in the 'main' content area.
value_box()
for highlighting values.
Other Dashboard page layouts:
page_navbar()
,
page_sidebar()
library(shiny) library(ggplot2) ui <- page_fillable( h1("Example", code("mtcars"), "dashboard"), layout_columns( card( full_screen = TRUE, card_header("Number of forward gears"), plotOutput("gear") ), card( full_screen = TRUE, card_header("Number of carburetors"), plotOutput("carb") ) ), card( full_screen = TRUE, card_header("Weight vs. Quarter Mile Time"), layout_sidebar( sidebar = sidebar( varSelectInput("var_x", "Compare to qsec:", mtcars[-7], "wt"), varSelectInput("color", "Color by:", mtcars[-7], "cyl"), position = "right" ), plotOutput("var_vs_qsec") ) ) ) server <- function(input, output) { for (var in c("cyl", "vs", "am", "gear", "carb")) { mtcars[[var]] <- as.factor(mtcars[[var]]) } output$gear <- renderPlot({ ggplot(mtcars, aes(gear)) + geom_bar() }) output$carb <- renderPlot({ ggplot(mtcars, aes(carb)) + geom_bar() }) output$var_vs_qsec <- renderPlot({ req(input$var_x, input$color) ggplot(mtcars) + aes(y = qsec, x = !!input$var_x, color = !!input$color) + geom_point() }) } shinyApp(ui, server)
library(shiny) library(ggplot2) ui <- page_fillable( h1("Example", code("mtcars"), "dashboard"), layout_columns( card( full_screen = TRUE, card_header("Number of forward gears"), plotOutput("gear") ), card( full_screen = TRUE, card_header("Number of carburetors"), plotOutput("carb") ) ), card( full_screen = TRUE, card_header("Weight vs. Quarter Mile Time"), layout_sidebar( sidebar = sidebar( varSelectInput("var_x", "Compare to qsec:", mtcars[-7], "wt"), varSelectInput("color", "Color by:", mtcars[-7], "cyl"), position = "right" ), plotOutput("var_vs_qsec") ) ) ) server <- function(input, output) { for (var in c("cyl", "vs", "am", "gear", "carb")) { mtcars[[var]] <- as.factor(mtcars[[var]]) } output$gear <- renderPlot({ ggplot(mtcars, aes(gear)) + geom_bar() }) output$carb <- renderPlot({ ggplot(mtcars, aes(carb)) + geom_bar() }) output$var_vs_qsec <- renderPlot({ req(input$var_x, input$color) ggplot(mtcars) + aes(y = qsec, x = !!input$var_x, color = !!input$color) + geom_point() }) } shinyApp(ui, server)
Create a dashboard layout with a full-width header (title
) and sidebar()
.
page_sidebar( ..., sidebar = NULL, title = NULL, fillable = TRUE, fillable_mobile = FALSE, theme = bs_theme(), window_title = NA, lang = NULL )
page_sidebar( ..., sidebar = NULL, title = NULL, fillable = TRUE, fillable_mobile = FALSE, theme = bs_theme(), window_title = NA, lang = NULL )
... |
UI elements to display in the 'main' content area (i.e., next to
the |
sidebar |
A |
title |
A string, number, or |
fillable |
Whether or not the |
fillable_mobile |
Whether or not the page should fill the viewport's height on mobile devices (i.e., narrow windows). |
theme |
A |
window_title |
the browser window title. The default value, |
lang |
ISO 639-1 language code for the HTML page, such as "en" or "ko".
This will be used as the lang in the |
Getting Started with Dashboards on the bslib website.
layout_columns()
and layout_column_wrap()
for laying out content
into rows and columns.
accordion()
for grouping related input controls in the sidebar
.
card()
for wrapping outputs in the 'main' content area.
value_box()
for highlighting values.
Other Dashboard page layouts:
page_fillable()
,
page_navbar()
library(shiny) library(ggplot2) ui <- page_sidebar( title = "Example dashboard", sidebar = sidebar( varSelectInput("var", "Select variable", mtcars) ), card( full_screen = TRUE, card_header("My plot"), plotOutput("p") ) ) server <- function(input, output) { output$p <- renderPlot({ ggplot(mtcars) + geom_histogram(aes(!!input$var)) }) } shinyApp(ui, server)
library(shiny) library(ggplot2) ui <- page_sidebar( title = "Example dashboard", sidebar = sidebar( varSelectInput("var", "Select variable", mtcars) ), card( full_screen = TRUE, card_header("My plot"), plotOutput("p") ) ) server <- function(input, output) { output$p <- renderPlot({ ggplot(mtcars) + geom_histogram(aes(!!input$var)) }) } shinyApp(ui, server)
Display additional information when clicking on a UI element (typically a button).
popover( trigger, ..., title = NULL, id = NULL, placement = c("auto", "top", "right", "bottom", "left"), options = list() ) toggle_popover(id, show = NULL, session = get_current_session()) update_popover(id, ..., title = NULL, session = get_current_session())
popover( trigger, ..., title = NULL, id = NULL, placement = c("auto", "top", "right", "bottom", "left"), options = list() ) toggle_popover(id, show = NULL, session = get_current_session()) update_popover(id, ..., title = NULL, session = get_current_session())
trigger |
The UI element to serve as the popover trigger (typically a
|
... |
UI elements for the popover's body. Character strings are
automatically escaped unless marked as
|
title |
A title (header) for the popover. To remove a header
with |
id |
A character string. Required to re-actively respond to the
visibility of the popover (via the |
placement |
The placement of the popover relative to its trigger. |
options |
A list of additional options. |
show |
Whether to show ( |
session |
A Shiny session object (the default should almost always be used). |
popover()
: Add a popover to a UI element
toggle_popover()
: Programmatically show/hide a popover.
update_popover()
: Update the contents of a popover.
In addition to clicking the close_button
, popovers can be closed by
pressing the Esc/Space key when the popover (and/or its trigger) is
focused.
Like other bslib components, popovers can be themed by supplying
relevant theming variables
to bs_theme()
,
which effects styling of every popover on the page.
To style a specific popover differently from other popover, utilize the customClass
option:
popover( "Trigger", "Popover message", options = list(customClass = "my-pop") )
And then add relevant rules to bs_theme()
via bs_add_rules()
:
bs_theme() |> bs_add_rules(".my-pop { max-width: none; }")
Because the user needs to interact with the trigger
element to see the popover, it's best practice to use an element that is typically accessible via keyboard interactions, like a button or a link.
If you use a non-interactive element, like a <span>
or text, bslib will automatically add the tabindex="0"
attribute to the trigger element to make sure that users can reach the element with the keyboard.
This means that in most cases you can use any element you want as the trigger.
One place where it's important to consider the accessibility of the trigger is when using an icon without any accompanying text. In these cases, many R packages that provide icons will create an icon element with the assumption that the icon is decorative, which will make it inaccessible to users of assistive technologies.
When using an icon as the primary trigger, ensure that the icon does not have aria-hidden="true"
or role="presentation"
attributes.
Icon packages typically provide a way to specify a title for the icon, as well as a way to specify that the icon is not decorative.
The title should be a short description of the purpose of the trigger, rather than a description of the icon itself.
If you're using bsicons::bs_icon()
, provide a title
.
If you're using fontawesome::fa()
, set a11y = "sem"
and provide a title
.
For example:
popover( bsicons::bs_icon("gear", title = "Settings"), title = "Settings", sliderInput("n", "Number of points", 1, 100, 50) )
popover( fontawesome::fa("gear", a11y = "sem", title = "Settings"), title = "Settings", sliderInput("n", "Number of points", 1, 100, 50) )
Popovers are based on Bootstrap's Popover component. See the bslib website for an interactive introduction to tooltips and popovers.
tooltip()
provides an alternative way to display informational
text on demand, typically when focusing or hovering over a trigger element.
Other Components:
accordion()
,
card()
,
tooltip()
,
value_box()
popover( shiny::actionButton("btn", "A button"), "Popover body content...", title = "Popover title" ) library(shiny) ui <- page_fixed( card(class = "mt-5", card_header( popover( uiOutput("card_title", inline = TRUE), title = "Provide a new title", textInput("card_title", NULL, "An editable title") ) ), "The card body..." ) ) server <- function(input, output) { output$card_title <- renderUI({ list(input$card_title, bsicons::bs_icon("pencil-square")) }) } shinyApp(ui, server)
popover( shiny::actionButton("btn", "A button"), "Popover body content...", title = "Popover title" ) library(shiny) ui <- page_fixed( card(class = "mt-5", card_header( popover( uiOutput("card_title", inline = TRUE), title = "Provide a new title", textInput("card_title", NULL, "An editable title") ) ), "The card body..." ) ) server <- function(input, output) { output$card_title <- renderUI({ list(input$card_title, bsicons::bs_icon("pencil-square")) }) } shinyApp(ui, server)
A 'real-time' theme customization UI that you can use to easily make common
tweaks to Bootstrap variables and immediately see how they would affect your
app's appearance. There are two ways you can launch the theming UI. For most
Shiny apps, just use run_with_themer()
in place of shiny::runApp()
; they
should take the same arguments and work the same way. Alternatively, you can
call the bs_themer()
function from inside your server function (or in an R
Markdown app that is using runtime: shiny
, you can call this from any code
chunk). Note that this function is only intended to be used for development!
run_with_themer(appDir = getwd(), ..., gfonts = TRUE, gfonts_update = FALSE) bs_themer(gfonts = TRUE, gfonts_update = FALSE)
run_with_themer(appDir = getwd(), ..., gfonts = TRUE, gfonts_update = FALSE) bs_themer(gfonts = TRUE, gfonts_update = FALSE)
appDir |
The application to run. This can be a file or directory path,
or a |
... |
Additional parameters to pass through to |
gfonts |
whether or not to detect Google Fonts and wrap them in
|
gfonts_update |
whether or not to update the internal database of Google Fonts. |
To help you utilize the changes you see in the preview, this utility prints
bs_theme()
code to the R console.
nothing. These functions are called for their side-effects.
Doesn't work with Bootstrap 3.
Doesn't work with IE11.
Only works inside Shiny apps and runtime: shiny
R Markdown documents.
Can't be used with static R Markdown documents.
Can be used to some extent with runtime: shiny_prerendered
, but only UI
rendered through a context="server"
may update in real-time.
Doesn't work with '3rd party' custom widgets that don't make use of
bs_dependency_defer()
or bs_current_theme()
.
library(shiny) ui <- fluidPage( theme = bs_theme(bg = "black", fg = "white"), h1("Heading 1"), h2("Heading 2"), p( "Paragraph text;", tags$a(href = "https://www.rstudio.com", "a link") ), p( actionButton("cancel", "Cancel"), actionButton("continue", "Continue", class = "btn-primary") ), tabsetPanel( tabPanel("First tab", "The contents of the first tab" ), tabPanel("Second tab", "The contents of the second tab" ) ) ) if (interactive()) { run_with_themer(shinyApp(ui, function(input, output) {})) }
library(shiny) ui <- fluidPage( theme = bs_theme(bg = "black", fg = "white"), h1("Heading 1"), h2("Heading 2"), p( "Paragraph text;", tags$a(href = "https://www.rstudio.com", "a link") ), p( actionButton("cancel", "Cancel"), actionButton("continue", "Continue", class = "btn-primary") ), tabsetPanel( tabPanel("First tab", "The contents of the first tab" ), tabPanel("Second tab", "The contents of the second tab" ) ) ) if (interactive()) { run_with_themer(shinyApp(ui, function(input, output) {})) }
Sidebar layouts place UI elements, like input controls or additional context, next to the main content area which often holds output elements like plots or tables.
There are several page, navigation, and layout functions that allow you to
create a sidebar layout. In each case, you can create a collapsing sidebar
layout by providing a sidebar()
object to the sidebar
argument the
following functions.
page_sidebar()
creates a "page-level" sidebar.
page_navbar()
creates a multi-panel app with an (optional, page-level)
sidebar that is shown on every panel.
layout_sidebar()
creates a "floating" sidebar layout component which can
be used inside any page()
and/or card()
context.
navset_card_tab()
and navset_card_pill()
create multi-tab cards with a
shared sidebar that is accessible from every panel.
See the Sidebars article on the bslib website to learn more.
sidebar( ..., width = 250, position = c("left", "right"), open = NULL, id = NULL, title = NULL, bg = NULL, fg = NULL, class = NULL, max_height_mobile = NULL, gap = NULL, padding = NULL ) layout_sidebar( ..., sidebar = NULL, fillable = TRUE, fill = TRUE, bg = NULL, fg = NULL, border = NULL, border_radius = NULL, border_color = NULL, padding = NULL, gap = NULL, height = NULL ) toggle_sidebar(id, open = NULL, session = get_current_session())
sidebar( ..., width = 250, position = c("left", "right"), open = NULL, id = NULL, title = NULL, bg = NULL, fg = NULL, class = NULL, max_height_mobile = NULL, gap = NULL, padding = NULL ) layout_sidebar( ..., sidebar = NULL, fillable = TRUE, fill = TRUE, bg = NULL, fg = NULL, border = NULL, border_radius = NULL, border_color = NULL, padding = NULL, gap = NULL, height = NULL ) toggle_sidebar(id, open = NULL, session = get_current_session())
... |
Unnamed arguments can be any valid child of an htmltools tag and named arguments become HTML attributes on
returned UI element. In the case of |
width |
A valid CSS unit used for the width of the sidebar. |
position |
Where the sidebar should appear relative to the main content. |
open |
The initial state of the sidebar, choosing from the following options:
Alternatively, you can use a list with In |
id |
A character string. Required if wanting to re-actively read (or
update) the |
title |
A character title to be used as the sidebar title, which will be
wrapped in a |
bg , fg
|
A background or foreground color. If only one of either is
provided, an accessible contrasting color is provided for the opposite
color, e.g. setting |
class |
CSS classes for the sidebar container element, in addition to
the fixed |
max_height_mobile |
A CSS length unit
defining the maximum height of the horizontal sidebar when viewed on mobile
devices. Only applies to always-open sidebars that use |
gap |
A CSS length unit defining the
vertical |
padding |
Padding within the sidebar itself. This can be a numeric
vector (which will be interpreted as pixels) or a character vector with
valid CSS lengths. |
sidebar |
A |
fillable |
Whether or not the |
fill |
Whether or not to allow the layout container to grow/shrink to fit a
fillable container with an opinionated height (e.g., |
border |
Whether or not to add a border. |
border_radius |
Whether or not to add a border radius. |
border_color |
The border color that is applied to the entire layout (if
|
height |
Any valid CSS unit (e.g.,
|
session |
A Shiny session object (the default should almost always be used). |
toggle_sidebar()
: Toggle a sidebar()
state during an active Shiny user
session.
Sidebar layouts are featured in a number of pages on the bslib website:
Obtain a theme's Bootswatch theme name
theme_bootswatch(theme)
theme_bootswatch(theme)
theme |
A |
Returns the Bootswatch theme named used (if any) in the theme
.
Other Bootstrap theme utility functions:
bootswatch_themes()
,
bs_get_variables()
,
builtin_themes()
,
theme_version()
,
versions()
Obtain a theme's Bootstrap version
theme_version(theme)
theme_version(theme)
theme |
A |
Returns the major version of Bootstrap used in the theme
.
Other Bootstrap theme utility functions:
bootswatch_themes()
,
bs_get_variables()
,
builtin_themes()
,
theme_bootswatch()
,
versions()
Display additional information when focusing (or hovering over) a UI element.
tooltip( trigger, ..., id = NULL, placement = c("auto", "top", "right", "bottom", "left"), options = list() ) toggle_tooltip(id, show = NULL, session = get_current_session()) update_tooltip(id, ..., session = get_current_session())
tooltip( trigger, ..., id = NULL, placement = c("auto", "top", "right", "bottom", "left"), options = list() ) toggle_tooltip(id, show = NULL, session = get_current_session()) update_tooltip(id, ..., session = get_current_session())
trigger |
A UI element (i.e., htmltools tag) to serve
as the tooltip trigger. If |
... |
UI elements for the tooltip. Character strings are automatically escaped unless marked as |
id |
a character string that matches an existing tooltip id. |
placement |
The placement of the tooltip relative to its trigger. |
options |
A list of additional options. |
show |
Whether to show ( |
session |
A Shiny session object (the default should almost always be used). |
tooltip()
: Add a tooltip to a UI element
toggle_tooltip()
: Programmatically show/hide a tooltip.
update_tooltip()
: Update the contents of a tooltip.
Like other bslib components, tooltips can be themed by supplying
relevant theming variables
to bs_theme()
,
which effects styling of every tooltip on the page.
To style a specific tooltip differently from other tooltip, utilize the customClass
option:
tooltip( "Trigger", "Tooltip message", options = list(customClass = "my-tip") )
And then add relevant rules to bs_theme()
via bs_add_rules()
:
bs_theme() |> bs_add_rules(".my-tip { max-width: none; }")
Because the user needs to interact with the trigger
element to see the tooltip, it's best practice to use an element that is typically accessible via keyboard interactions, like a button or a link.
If you use a non-interactive element, like a <span>
or text, bslib will automatically add the tabindex="0"
attribute to the trigger element to make sure that users can reach the element with the keyboard.
This means that in most cases you can use any element you want as the trigger.
One place where it's important to consider the accessibility of the trigger is when using an icon without any accompanying text. In these cases, many R packages that provide icons will create an icon element with the assumption that the icon is decorative, which will make it inaccessible to users of assistive technologies.
When using an icon as the primary trigger, ensure that the icon does not have aria-hidden="true"
or role="presentation"
attributes.
Icon packages typically provide a way to specify a title for the icon, as well as a way to specify that the icon is not decorative.
The title should be a short description of the purpose of the trigger, rather than a description of the icon itself.
If you're using bsicons::bs_icon()
, provide a title
.
If you're using fontawesome::fa()
, set a11y = "sem"
and provide a title
.
For example:
tooltip( bsicons::bs_icon("info-circle", title = "About tooltips"), "Text shown in the tooltip." )
tooltip( fontawesome::fa("info-circle", a11y = "sem", title = "About tooltips"), "Text shown in the tooltip." )
Tooltips are based on Bootstrap's Tooltip component. See the bslib website for an interactive introduction to tooltips and popovers.
popover()
provides a an alternative and more persistent container
for additional elements, typically revealed by clicking on a target
element.
Other Components:
accordion()
,
card()
,
popover()
,
value_box()
tooltip( shiny::actionButton("btn", "A button"), "A message" ) card( card_header( tooltip( span("Card title ", bsicons::bs_icon("question-circle-fill")), "Additional info", placement = "right" ) ), "Card body content..." )
tooltip( shiny::actionButton("btn", "A button"), "A message" ) card( card_header( tooltip( span("Card title ", bsicons::bs_icon("question-circle-fill")), "Additional info", placement = "right" ) ), "Card body content..." )
An opinionated (card()
-powered) box, designed for displaying a value
and
title
. Optionally, a showcase
can provide for context for what the
value
represents (for example, it could hold a bsicons::bs_icon()
, or
even a shiny::plotOutput()
). Find examples and template code you can use to
create engaging value boxes on the bslib website.
value_box( title, value, ..., showcase = NULL, showcase_layout = c("left center", "top right", "bottom"), full_screen = FALSE, theme = NULL, height = NULL, max_height = NULL, min_height = NULL, fill = TRUE, class = NULL, id = NULL, theme_color = deprecated() ) value_box_theme(name = NULL, bg = NULL, fg = NULL) showcase_left_center( width = 0.3, width_full_screen = "1fr", max_height = "100px", max_height_full_screen = 0.67 ) showcase_top_right( width = 0.4, width_full_screen = "1fr", max_height = "75px", max_height_full_screen = 0.67 ) showcase_bottom( width = "100%", width_full_screen = NULL, height = "auto", height_full_screen = "2fr", max_height = "100px", max_height_full_screen = NULL )
value_box( title, value, ..., showcase = NULL, showcase_layout = c("left center", "top right", "bottom"), full_screen = FALSE, theme = NULL, height = NULL, max_height = NULL, min_height = NULL, fill = TRUE, class = NULL, id = NULL, theme_color = deprecated() ) value_box_theme(name = NULL, bg = NULL, fg = NULL) showcase_left_center( width = 0.3, width_full_screen = "1fr", max_height = "100px", max_height_full_screen = 0.67 ) showcase_top_right( width = 0.4, width_full_screen = "1fr", max_height = "75px", max_height_full_screen = 0.67 ) showcase_bottom( width = "100%", width_full_screen = NULL, height = "auto", height_full_screen = "2fr", max_height = "100px", max_height_full_screen = NULL )
title , value
|
A string, number, or |
... |
Unnamed arguments may be any |
showcase |
A |
showcase_layout |
One of |
full_screen |
If |
theme |
The name of a theme for the value box, or a theme constructed
with |
max_height |
The maximum height of the |
min_height |
The minimum height of the values box. Can be any valid CSS unit (e.g., |
fill |
Whether to allow the value box to grow/shrink to fit a fillable
container with an opinionated height (e.g., |
class |
Utility classes for customizing the appearance of the summary
card. Use |
id |
Provide a unique identifier for the |
theme_color |
|
name |
The name of the theme, e.g. |
bg , fg
|
The background and foreground colors for the theme. If only |
width , width_full_screen , height , height_full_screen
|
one of the following:
|
max_height_full_screen |
A proportion (i.e., a number between
0 and 1) or any valid CSS unit defining the
showcase |
Explore all of the value_box()
options and layouts interactively with the
Build-a-Box app, available
online thanks to shinyapps.io. Or, you can
run the app locally with:
# shiny >= 1.8.1 shiny::runExample("build-a-box", package = "bslib") # shiny < 1.8.1 shiny::runApp(system.file("examples-shiny", "build-a-box", package = "bslib"))
The appearance of a value_box()
can be controlled via the theme
argument
in one of two ways:
a character value describing the theme,
such as theme = "primary"
or theme = "blue"
; or
theme = value_box_theme()
to create a custom theme.
We recommend using named themes for most value boxes (the first approach), because these themes will automatically match your Bootstrap theme.
Bootstrap provides a list of
theme colors,
with semantic names like "primary"
, "secondary"
, "success"
, "danger"
, etc.
You can set theme
to one of these names to use the corresponding theme color as the background color of your value box.
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "primary" )
Bootstrap's theme colors are drawn from
a second color list
that includes variations on several main colors,
named literally.
These colors include "blue"
, "purple"
, "pink"
, "red"
, "orange"
,
"yellow"
, "green"
, "teal"
, and "cyan"
.
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "teal" )
If the theme or color name is provided without any prefix, the color will be used for the background of the value box.
You can also explicitly prefix the theme or color name with bg-
to indicate that it should apply to the value box background.
When the theme sets the background color, either black or white is chosen automatically for the text color using Bootstrap's color contrast algorithm.
As before, you can reference semantic theme color names or literal color names.
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "bg-success" )
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "bg-purple" )
To set only the foreground colors of the value box, you can prefix the theme or color name with text-
.
This changes the text color without affecting the background color.
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "text-success" )
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "text-purple" )
Occasionally you may want to adjust use both background and foreground themes on your value box.
To achieve this, set theme
to one of the theme names and use class
for the complementary style.
The example below uses theme = "purple"
(which could also be "bg-purple"
) for a purple background, and class = "text-light"
for light-colored text.
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "purple", class = "text-light" )
For a vibrant and attention-grabbing effect, bslib provides an array of gradient
background options.
Provide theme
with a theme name in the form bg-gradient-{from}-{to}
, where {from}
and {to}
are named main colors, e.g. bg-gradient-indigo-blue
.
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = "bg-gradient-indigo-blue" )
Finally, for complete customization, you can use value_box_theme()
to create a custom theme.
This function takes arguments bg
and fg
to set the background and foreground colors, respectively.
Like with the bg-
theme names, if only bg
is provided, value_box_theme()
will choose an appropriate light or dark color for the text color.
value_box( title = "Customer lifetime value", value = "$5,000", showcase = bsicons::bs_icon("bank2"), theme = value_box_theme(bg = "#e6f2fd", fg = "#0B538E"), class = "border" )
Note that value_box_theme()
optionally takes a theme
name, which can be helpful if you want to use a named theme and modify the default bg
or fg
colors of that theme.
value_box_theme(name = "orange", bg = "#FFFFFF") value_box_theme(name = "text-danger", fg = "#FFB6C1")
Also note that bg
/fg
must be CSS colors, not Bootstrap theme or color names.
This means that theme = "purple"
will use your Bootstrap theme's purple color, and bg = "purple"
will use the CSS color for purple, i.e. "#800080"
.
Use the showcase
argument to add a plot or icon to your value_box()
.
There are three layouts available: "left center"
, "top right"
, and "bottom"
.
Set showcase
to the name of the layout you'd like, or use the showcase_left_center()
, showcase_top_right()
, or showcase_bottom()
helper functions to customize the showcase area's size.
If you're using a plot as your showcase, you may also want to set fullscreen = TRUE
so that your users can expand the value box into a full screen card.
See the value box article for more details.
The "left center"
showcase layout is the default, and is perfect for an icon or a small plot.
This layout works best for short value boxes.
value_box( title = "Energy consumption", value = "345 kwh/month", showcase = bsicons::bs_icon("ev-station-fill") )
The "top right"
showcase layout places the icon or plot in the upper right corner of the value box.
This layout works best for medium-height to square value boxes.
value_box( title = "Energy consumption", value = "345 kwh/month", showcase = bsicons::bs_icon("ev-station-fill"), showcase_layout = "top right" )
Finally, the "bottom"
showcase layout is perfect for full-bleed plots.
This layout places the plot below the title and value, with the plot taking up the full width of the bottom half.
Try this layout with sparkline-style plots. These can be a little tricky to set up, so be sure to check out the Expandable sparklines section of the value boxes article on the bslib website. In this example, we've created a sparkline plot using base R graphics, which isn't generally recommended.
set.seed(4242)
random_sparkline_plot <- function() {
timeseries <- cumsum(runif(100, -2, 2))
x_axis <- seq_along(timeseries)
x_lim <- c(1, length(timeseries))
y_lim <- range(timeseries) + c(-2, 0)
par(mar = c(0, 0, 0, 0))
# Set up the plot area
plot(
timeseries, type = "n",
axes = FALSE, frame.plot = FALSE,
ylim = y_lim, xlim = x_lim,
ylab = "", xlab = "",
yaxs = "i", xaxs = "i",
)
# Add the sparkline line
lines(timeseries, type = "l", pch = NA, col = "#0B538E", lwd = 3)
# Create polygon coordinates for shading
polygon_x <- c(1, x_axis, length(timeseries))
polygon_y <- c(min(y_lim), timeseries, min(y_lim))
# Add shading under the line
polygon(polygon_x, polygon_y, col = "#e6f2fd", border = NA)
}
sparkline_plot <- function() {
as_fill_item(
htmltools::plotTag(
random_sparkline_plot(),
width = 500,
height = 125,
suppressSize = "xy",
alt = paste(
"A sparkline plot with a randomly-generated timeseries.",
"The timeseries starts high and ends low, with lots of variation."
)
)
)
}
value_box( title = "Energy consumption", value = "345 kwh/month", showcase = sparkline_plot(), showcase_layout = "bottom" )
Value boxes are featured on the bslib website in a few articles:
Value boxes are a specialized form of a card()
component.
layout_columns()
and layout_column_wrap()
help position multiple
value boxes into columns and rows.
Other Components:
accordion()
,
card()
,
popover()
,
tooltip()
library(htmltools) value_box( "KPI Title", h1(HTML("$1 <i>Billion</i> Dollars")), span( bsicons::bs_icon("arrow-up"), " 30% VS PREVIOUS 30 DAYS" ), showcase = bsicons::bs_icon("piggy-bank"), theme = "success" )
library(htmltools) value_box( "KPI Title", h1(HTML("$1 <i>Billion</i> Dollars")), span( bsicons::bs_icon("arrow-up"), " 30% VS PREVIOUS 30 DAYS" ), showcase = bsicons::bs_icon("piggy-bank"), theme = "success" )
Available Bootstrap versions
versions() version_default()
versions() version_default()
Returns a list of the Bootstrap versions available.
Other Bootstrap theme utility functions:
bootswatch_themes()
,
bs_get_variables()
,
builtin_themes()
,
theme_bootswatch()
,
theme_version()