Debian Codegraph @

R/layers.R

raw
1 #' @importFrom rlang list2 names2 %||%
2 NULL
3
4 #' Bundling Sass layers
5 #'
6 #' Sass layers provide a way to package Sass variables, rules, functions, and
7 #' mixins in a structured and composable way that follows best Sass practices.
8 #' Most importantly, when multiple `sass_layer()` are combined into a
9 #' `sass_bundle()`, variable `defaults` for later layers are placed _before_
10 #' earlier layers, effectively 'new' defaults through all the 'old' defaults.
11 #'
12 #' @param functions [sass::as_sass()] `input` intended for [Sass
13 #' functions](https://rstudio.github.io/sass/articles/sass.html#functions-1).
14 #' Functions are placed before `defaults` so that variable definitions may make
15 #' use of functions.
16 #' @param defaults [sass::as_sass()] `input` intended for [variable
17 #' defaults](https://rstudio.github.io/sass/articles/sass.html#variables-1).
18 #' These variable defaults after placed after `functions` but before `mixins`.
19 #' When multiple layers are combined in a `sass_bundle()`, defaults are merged
20 #' in reverse order; that is, `sass_bundle(layer1, layer2)` will include
21 #' `layer2$defaults` before `layer1$defaults`.
22 #' @param mixins [sass::as_sass()] `input` intended for [Sass
23 #' mixins](https://rstudio.github.io/sass/articles/sass.html#mixins-1). Mixins
24 #' are placed after `defaults`, but before `rules`.
25 #' @param rules [sass::as_sass()] `input` intended for [Sass
26 #' rules](https://sass-lang.com/documentation/style-rules). Rules are placed last
27 #' (i.e., after `functions`, `defaults`, and `mixins`).
28 #' @param html_deps An HTML dependency (or a list of them). This dependency
29 #' gets attached to the return value of [sass()]/[as_sass()].
30 #' @param file_attachments A named character vector, representing file assets
31 #' that are referenced (using relative paths) from the sass in this layer. The
32 #' vector names should be a relative path, and the corresponding vector values
33 #' should be absolute paths to files or directories that exist; at render
34 #' time, each value will be copied to the relative path indicated by its name.
35 #' (For directories, the _contents_ of the source directory will be copied
36 #' into the destination directory; the directory itself will not be copied.)
37 #' You can also omit the name, in which case that file or directory will be
38 #' copied directly into the output directory.
39 #' @param declarations Deprecated, use `functions` or `mixins` instead.
40 #' @param tags Deprecated. Preserve meta information using a key in `sass_bundle(KEY = val)`.
41 #' preserve simple metadata as layers are merged.
42 #' @md
43 #' @examples
44 #' blue <- list(color = "blue !default")
45 #' red <- list(color = "red !default")
46 #' green <- list(color = "green !default")
47 #'
48 #' # a sass_layer() by itself is not very useful, it just defines some
49 #' # SASS to place before (defaults) and after (rules)
50 #' core <- sass_layer(defaults = blue, rules = "body { color: $color; }")
51 #' core
52 #' sass(core)
53 #'
54 #' # However, by stacking sass_layer()s, we have ability to place
55 #' # SASS both before and after some other sass (e.g., core)
56 #' # Here we place a red default _before_ the blue default and export the
57 #' # color SASS variable as a CSS variable _after_ the core
58 #' red_layer <- sass_layer(red, rules = ":root{ --color: #{$color}; }")
59 #' sass(sass_bundle(core, red_layer))
60 #' sass(sass_bundle(core, red_layer, sass_layer(green)))
61 #'
62 #' # Example of merging layers and removing a layer
63 #' # Remember to name the layers that are removable
64 #' core_layers <- sass_bundle(core, red = red_layer, green = sass_layer(green))
65 #' core_layers # pretty printed for console
66 #' core_slim <- sass_bundle_remove(core_layers, "red")
67 #' sass(core_slim)
68 #'
69 #'
70 #' # File attachment example: Create a checkboard pattern .png, then
71 #' # use it from a sass layer
72 #'
73 #' tmp_png <- tempfile(fileext = ".png")
74 #' grDevices::png(filename = tmp_png, width = 20, height = 20,
75 #' bg = "transparent", antialias = "none")
76 #' par(mar = rep_len(0,4), xaxs = "i", yaxs = "i")
77 #' plot.new()
78 #' rect(c(0,0.5), c(0,0.5), c(0.5,1), c(0.5,1), col = "#00000044", border=NA)
79 #' dev.off()
80 #'
81 #' layer <- sass_layer(
82 #' rules = ".bg-check { background-image: url(images/demo_checkboard_bg.png) }",
83 #' file_attachments = c("images/demo_checkboard_bg.png" = tmp_png)
84 #' )
85 #'
86 #' output_path <- tempfile(fileext = ".css")
87 #' sass(layer, output = output_path, write_attachments = TRUE)
88 #' @describeIn sass_layer Compose the parts of a single Sass layer. Object returned is a `sass_bundle()` with a single Sass layer
89 #' @export
90 sass_layer <- function(
91 functions = NULL,
92 defaults = NULL,
93 mixins = NULL,
94 rules = NULL,
95 html_deps = NULL,
96 file_attachments = character(0),
97 declarations = NULL,
98 tags = NULL
99 ) {
100
101 # In a future release cycle (once bslib has been updated to not use
102 # declarations), then consider throwing this deprecation message
103 #if (!is.null(declarations)) {
104 # .Deprecated(msg="`declarations` is deprecated. Please use `functions` or `mixins instead.`")
105 #}
106
107 if (!missing(tags)) {
108 .Deprecated(msg="`sass_layer(tags)` is deprecated. Please use a named layer in a `sass_bundle(NAME = layer)`")
109 }
110
111 # return a size 1 sass_bundle()
112 as_sass_bundle(
113 sass_layer_struct(
114 functions = functions,
115 defaults = defaults,
116 mixins = mixins,
117 rules = rules,
118 declarations = declarations,
119 html_deps = html_deps,
120 file_attachments = file_attachments
121 )
122 )
123 }
124
125
126 #' @export
127 #' @param file file path to a `.scss` file.
128 #' @describeIn sass_layer Read in a `.scss` file with parse special `/*-- scss:(functions|defaults|rules|mixins) --*/` comments as relevant sections of a `sass_layer()`.
129 sass_layer_file <- function(file) {
130 src <- readLines(file)
131 # https://github.com/quarto-dev/quarto-cli/blob/3d6063/src/command/render/sass.ts#L119-L123
132 pattern_key <- "scss:(functions|defaults|rules|mixins)"
133 pattern <- paste0("^/\\*--[ \\t]*", pattern_key, "[ \\t]*--\\*/$")
134 idx <- grep(pattern, src)
135 if (length(idx) == 0) {
136 return(sass_layer(rules = src))
137 }
138 types <- extract_group(src[idx], pattern_key)
139 utypes <- unique(types)
140 args <- rlang::set_names(vector("list", length(utypes)), utypes)
141 for (i in seq_along(idx)) {
142 start <- idx[i] + 1
143 end <- if (i == length(idx)) length(src) else (idx[i + 1] - 1)
144 type <- types[i]
145 args[[type]] <- c(args[[type]], src[seq.int(start, end)])
146 }
147 do.call(sass_layer, args)
148 }
149
150 #' Helps avoid sass_layer / sass_bundle inf recursion
151 #' @return object of class `sass_layer`
152 #' @noRd
153 sass_layer_struct <- function(
154 functions = NULL,
155 defaults = NULL,
156 mixins = NULL,
157 rules = NULL,
158 declarations = NULL,
159 html_deps = NULL,
160 file_attachments = character(0),
161 validate = TRUE
162 ) {
163
164 if (validate) {
165 validate_layer_param(functions, "functions")
166 validate_layer_param(defaults, "defaults")
167 validate_layer_param(mixins, "mixins")
168 validate_layer_param(rules, "rules")
169 validate_layer_param(declarations, "declarations")
170
171 if (!is.null(html_deps)) {
172 if (is_dependency_maybe(html_deps)) {
173 html_deps <- list(html_deps)
174 }
175 if (!is.list(html_deps)) {
176 stop("`html_deps` must be a collection of htmlDependency() and/or tagFunction() objects")
177 }
178 is_dependency <- vapply(html_deps, is_dependency_maybe, logical(1))
179 if (any(!is_dependency)) {
180 stop("`html_deps` must be a collection of htmlDependency() and/or tagFunction() objects")
181 }
182 }
183 }
184
185 layer <- list(
186 functions = functions,
187 defaults = defaults,
188 mixins = mixins,
189 rules = rules,
190 declarations = declarations,
191 html_deps = html_deps,
192 file_attachments = file_attachments
193 )
194 add_class(layer, "sass_layer")
195 }
196
197 is_dependency_maybe <- function(x) {
198 inherits(x, "html_dependency") || inherits(x, "shiny.tag.function")
199 }
200
201 validate_layer_param <- function(x, name) {
202 bundle_item <- find_bundle_or_layer(x)
203 if (!is.null(bundle_item)) {
204 stop(
205 "`sass_layer(", name, ")` can not contain another `sass_bundle()` object.\n",
206 "Found:\n",
207 collapse0(utils::capture.output(print(bundle_item)))
208 )
209 }
210 }
211 is_sass_bundle_like <- function(x) {
212 is_sass_bundle(x) || is_sass_layer(x)
213 }
214
215 # returns the sass bundle like obj or NULL
216 find_bundle_or_layer <- function(x) {
217 if (!is.list(x)) return(NULL)
218 if (is_sass_bundle_like(x)) return(x)
219
220 # Recursively inspect list objects
221 # Use for loop to pre-empty calculations
222 for (item in x) {
223 if (is_sass_bundle_like(item)) return(item)
224 ret <- find_bundle_or_layer(item)
225 if (!is.null(ret)) return(ret)
226 }
227 return(NULL)
228 }
229
230
231 # @param x object to inspect or turn into Sass bundle
232 # @param name Sass layer name to use inside the Sass bundle object
233 as_sass_bundle <- function(x, name = "") {
234 stopifnot(is.character(name) && length(name) == 1)
235
236 # Upgrade pattern:
237 # is_sass_bundle(x) && name == "" -> x
238 # is_sass_bundle(x) && name != "" -> sass_bundle(!!name := as_sass_layer(x))
239 # is_sass_layer(x) -> sass_bundle(!!name := x)
240 # is.list(x) && has_any_name(x) -> sass_bundle(!!name := sass_layer(defaults = x))
241 # else -> sass_bundle(!!name := sass_layer(rules = x))
242
243 # A list of sass_layer values can be handled by sass_bundle(...) or sass_bundle(!!!x). Do not test for this
244
245 if (is_sass_bundle(x)) {
246 # if there is nothing special about the name, return
247 if (identical(name, "")) {
248 return(x)
249 }
250
251 # convert to a single sass layer object so the overall name can be used
252 x <- as_sass_layer(x)
253 }
254
255 single_layer <-
256 if (is_sass_layer(x)) {
257 x
258 } else {
259 # upgrade via sass_layer
260 if (is.list(x) && has_any_name_recursive(x)) {
261 # a name was found somewhere
262 sass_layer_struct(defaults = x)
263 } else {
264 sass_layer_struct(rules = x)
265 }
266 }
267
268 layers <- list()
269 layers[[name]] <- single_layer
270
271 sass_bundle_struct(layers = layers)
272 }
273
274 #' Helps avoid sass_bundle inf recursion
275 #' @param layers named or unnamed list containing sass_layer objects
276 #' @return object of class `sass_bundle`
277 #' @noRd
278 sass_bundle_struct <- function(layers = list()) {
279 layers_are_sass_layers <- vapply(layers, is_sass_layer, logical(1))
280 stopifnot(all(layers_are_sass_layers))
281 ret <- list(
282 layers = layers
283 )
284 class(ret) <- "sass_bundle"
285 ret
286 }
287
288 #' @describeIn sass_layer Collect `sass_bundle()` and/or `sass_layer()` objects. Unnamed Sass bundles will be concatenated together, preserving their internal name structures. Named Sass bundles will be condensed into a single Sass layer for easier removal from the returned Sass bundle.
289 #' @param ... A collection of `sass_layer()`s and/or objects that [sass::as_sass()]
290 #' understands. Arguments should be provided in reverse priority order:
291 #' defaults, declarations, and rules in later layers will take precedence over
292 #' those of previous layers. Non-layer values will be converted to layers by
293 #' calling `sass_layer(rules = ...)`.
294 #' @export
295 sass_bundle <- function(...) {
296 layers <- dropNulls(list2(...))
297 layers_upgraded <-
298 mapply(
299 SIMPLIFY = FALSE,
300 layers,
301 names2(layers),
302 FUN = function(x, name) {
303 as_sass_bundle(x, name = name)
304 }
305 )
306 # collect and flatten
307 ## unlist(list(list(1), list(), NULL, list(2)), recursive = FALSE)
308 #> [[1]]
309 #> [1] 1
310 #>
311 #> [[2]]
312 #> [1] 2
313 ret_layers <- unlist(
314 lapply(unname(layers_upgraded), `[[`, "layers"),
315 recursive = FALSE
316 )
317 sass_bundle_struct(ret_layers)
318 }
319
320
321 #' @describeIn sass_layer Remove a whole `sass_layer()` from a `sass_bundle()` object.
322 #' @param bundle Output value from `sass_layer()` or `sass_bundle()`
323 #' @param name If a Sass layer name is contained in `name`, the matching Sass layer will be removed from the `bundle`
324 #' @export
325 sass_bundle_remove <- function(bundle, name) {
326 stopifnot(is_sass_bundle(bundle))
327 if (!(
328 is.character(name) &&
329 all(!is.na(name)) &&
330 all(nzchar(name))
331 )) {
332 stop("`name` needs to be a character vector containing non-NA and non-empty values")
333 }
334
335 layer_names <- names(bundle$layers)
336 # vector support
337 layer_name_matches <- layer_names %in% name
338 if (any(layer_name_matches)) {
339 name_pos <- which(layer_name_matches)
340 bundle$layers <- bundle$layers[-1 * name_pos]
341 }
342 bundle
343 }
344
345
346 # sass_layer Check if `x` is a Sass layer object
347 is_sass_layer <- function(x) {
348 inherits(x, "sass_layer")
349 }
350
351 #' @describeIn sass_layer Check if `x` is a Sass bundle object
352 #' @param x object to inspect
353 #' @export
354 is_sass_bundle <- function(x) {
355 inherits(x, "sass_bundle")
356 }
357
358
359 #' Sass Bundle to Single Sass Layer
360 #'
361 #' Converts a [sass_bundle()] to a single Sass layer object.
362 #'
363 #' This is exported for internal use between packages and should not be used.
364 #' Instead, please use [sass_layer()] or [sass_bundle()] to construct and manage your sass objects
365 #' and [sass()] and [as_sass()] to convert your objects.
366 #'
367 #' @keywords internal
368 #' @export
369 as_sass_layer <- function(x) {
370 if (is_sass_layer(x)) return(x)
371 # sass_bundle(x) will auto upgrade to a sass bundle object
372 layers <- rlang::set_names(sass_bundle(x)$layers, NULL)
373 sass_layer_struct(
374 functions = pluck(layers, "functions"),
375 defaults = pluck(rev(layers), "defaults"),
376 mixins = pluck(layers, "mixins"),
377 rules = pluck(layers, "rules"),
378 declarations = pluck(layers, "declarations"),
379 html_deps = pluck(layers, "html_deps", .unlist = TRUE),
380 file_attachments = pluck(layers, "file_attachments", .unlist = TRUE),
381 validate = FALSE
382 )
383 }
384
385 pluck <- function(x, y, .unlist = FALSE) {
386 res <- dropNulls(lapply(x, `[[`, y))
387 if (length(res) == 0) {
388 return(NULL)
389 }
390 if (.unlist) {
391 res <- unlist(res, recursive = FALSE, use.names = TRUE)
392 }
393 res
394 }
395
396 extract_file_attachments <- function(x) {
397 if (is_sass_bundle_like(x)) {
398 return(as_sass_layer(x)$file_attachments)
399 }
400 if (!is.list(x)) {
401 return(NULL)
402 }
403 unlist(
404 lapply(x, extract_file_attachments),
405 recursive = FALSE, use.names = TRUE
406 )
407 }
408
409 validate_attachments <- function(attachments) {
410 if (is.null(attachments)) {
411 return()
412 }
413 if (!is.character(attachments)) {
414 stop("File attachments must be a character vector")
415 }
416 if (length(attachments) == 0) {
417 return()
418 }
419
420 dest <- names(attachments)
421 if (is.null(dest)) {
422 dest <- rep_len("", length(attachments))
423 }
424 src <- unname(attachments)
425
426 if (any(dest == "")) {
427 # Actually, unnamed attachments are OK; they'll just be
428 # copied to the output dir.
429 # stop("All file attachments must be named")
430 }
431
432 check_files <- function(files, ok, message) {
433 if (any(!ok)) {
434 stop(call. = FALSE, message, ": ",
435 paste0("'", files[!ok], "'", collapse = ", "))
436 }
437 }
438
439 check_files(dest, !fs::is_absolute_path(dest),
440 "File attachment names must be relative (destination) paths")
441
442 check_files(src, fs::is_absolute_path(src),
443 "File attachment names must be absolute (source) paths")
444
445 check_files(src, fs::file_exists(src),
446 "File attachments must exist")
447
448 check_files(dest, vapply(dest, fs::path_has_parent, logical(1), parent = "."),
449 "Illegal file attachment destination path(s)")
450 }
451
452
453 #' Write file attachments from a sass theme object
454 #'
455 #' @param file_attachments A character vector of files or directories.
456 #' @param output_path A directory to copy the attachments to.
457 #'
458 #' @keywords internal
459 #' @export
460 write_file_attachments <- function(file_attachments, output_path) {
461 validate_attachments(file_attachments)
462
463 if (!dir.exists(output_path)) {
464 stop(call. = FALSE,
465 "Directory '", output_path, "' not found or is not a directory")
466 }
467
468 output_path <- normalizePath(output_path, mustWork = TRUE)
469
470 mapply(function(dest, src) {
471 if (dir.exists(src)) {
472 dest <- file.path(output_path, dest)
473 if (!dir.exists(dest)) {
474 dir.create2(dest)
475 }
476 # We previously used fs::dir_copy(), but changed to file.copy2 for
477 # performance reasons. https://github.com/rstudio/sass/pull/53
478 file.copy2(
479 dir(src, all.files = TRUE, full.names = TRUE, no.. = TRUE),
480 dest,
481 overwrite = TRUE,
482 recursive = TRUE
483 )
484 return(NULL)
485 }
486
487 dest <- if (grepl("/$", dest)) {
488 # dest is intended to be a directory
489 file.path(output_path, dest, basename(src))
490 } else {
491 file.path(output_path, dest)
492 }
493
494 fs::dir_create(dirname(dest))
495 fs::file_copy(src, dest, overwrite = TRUE)
496
497 NULL
498 }, names(file_attachments), unname(file_attachments))
499
500 invisible()
501 }
502
503
504 dropNulls <- function(x) {
505 x[!vapply(x, is.null, FUN.VALUE=logical(1))]
506 }