Skip to content

Commit

Permalink
feat: Speed up get_color_contrast() (#1140)
Browse files Browse the repository at this point in the history
  • Loading branch information
gadenbuie authored Nov 25, 2024
1 parent c925ae5 commit a6fda93
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

* Fixed a bug in `bs_themer()` (and `bs_theme_preview()`) that caused it to stop applying changes if a Sass variable was `NULL`. (@meztez, #1112)

* Optimized for better performance the internal functions that compile Sass to call the `color-contrast()` algorithm. (#1140)

# bslib 0.8.0

## Breaking changes
Expand Down
Binary file modified R/sysdata.rda
Binary file not shown.
41 changes: 32 additions & 9 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,37 @@ rename2 <- function(x, ...) {
# Get an accessible color contrast for a specified bg_color
# (and return NULL+warn on failure)
get_color_contrast <- function(bg_color) {
# Use a specific name that won't clash with other variables
nm <- "__bslib-custom-bg-color__"
theme <- bs_add_variables(bs_theme(), !!nm := bg_color)
tryCatch(
bs_get_contrast(theme, nm)[[1]],
error = function(e) {
warning("Failed to compute a contrasting color for '", bg_color, "'", call. = FALSE)
NULL
}
utils_layer <- sass::sass_layer(
functions = sass::sass_file(
path_inst("sass-utils", "color-contrast.scss")
),
defaults = c(
"$black: #000000;",
"$white: #FFFFFF;"
),
rules = sprintf(
"._ {--RET: #{color-contrast(%s)}}",
bg_color
)
)

tryCatch({
css <- sass::sass(
utils_layer,
cache_key_extra = get_package_version("bslib"),
# Don't listen to global Sass options so we can be sure
# that stuff like source maps won't be included
options = sass::sass_options(source_map_embed = FALSE)
)
# example: css <- "._ {\n --RET: #fff;\n}"
# we'll split to get value: ^ ^
ret <- strsplit(css, "--RET:")[[1]][2]
trimws(strsplit(ret, ";")[[1]][1])
}, error = function(err) {
warning(
"Failed to compute a contrasting color for '", bg_color, "'",
call. = FALSE
)
NULL
})
}

0 comments on commit a6fda93

Please sign in to comment.