Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce bs_with_theme() and bs_local_theme() #108

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions R/theme-local.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#' Localized themes
#'
#' Tools for using bootstraplib themes in a localized manner. Use
#' `bs_with_theme()` to scope theming side-effects to the given `expr` and
#' `bs_local_theme()` to scope within a particular environment. This makes
#' `bs_local_theme()` handy for theming within a function that returns a shiny
#' app and `bs_with_theme()` handy for running "top-level" code at the R console
#' without introducing theming side-effects.
#'
#' @param expr theming code to evaluate in a localized fashion
#' @param .local_envir The environment to use for scoping.
#' @export
#' @examples
#'
#' theme <- bs_theme_get()
#' bs_with_theme({
#' bs_theme_new()
#' bs_theme_base_colors(bg = "black", fg = "white")
#' if (interactive()) shiny::runExample("01_hello")
#' })
#' identical(theme, bs_theme_get())
#'
#' my_app_func <- function() {
#' bs_local_theme({
#' bs_theme_new(3)
#' bs_theme_base_colors(bg = "black", fg = "white")
#' })
#' shinyApp(fluidPage("Howdy"), function(input, output) {})
#' }
#'
#' my_app_func()
#' identical(theme, bs_theme_get())
#'
bs_local_theme <- function(expr, .local_envir = parent.frame()) {
old_theme <- bs_theme_get()
withr::defer(bs_theme_set(old_theme), envir = .local_envir)
force(expr)
}

#' @rdname bs_local_theme
bs_with_theme <- function(expr) {
old_theme <- bs_theme_get()
on.exit(bs_theme_set(old_theme), add = TRUE)
force(expr)
}