From 6713001c6c7b232a9eeb20a671662325774fc60b Mon Sep 17 00:00:00 2001 From: Carson Date: Thu, 17 Sep 2020 17:20:57 -0500 Subject: [PATCH] Introduce bs_with_theme() and bs_local_theme() --- R/theme-local.R | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 R/theme-local.R diff --git a/R/theme-local.R b/R/theme-local.R new file mode 100644 index 000000000..4de136fd7 --- /dev/null +++ b/R/theme-local.R @@ -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) +}