Debian Codegraph @

inst/doc/sass.Rmd

raw
1 ---
2 title: "Overview of the sass R package"
3 author: "Carson Sievert"
4 date: "`r Sys.Date()`"
5 output: rmarkdown::html_vignette
6 vignette: >
7 %\VignetteIndexEntry{Overview of the sass R package}
8 %\VignetteEngine{knitr::rmarkdown}
9 %\VignetteEncoding{UTF-8}
10 ---
11
12 <style>
13 pre {
14 border: 1px solid #eee;
15 }
16
17 pre.r {
18 background-color: #ffffff;
19 margin-bottom: -0.5em;
20 }
21
22 pre.r code {
23 background-color: #ffffff;
24 }
25
26 pre.css {
27 background-color: #f8f8f8;
28 border-radius: 0;
29 border-bottom-left-radius: 4px;
30 border-bottom-right-radius: 4px;
31 }
32 </style>
33
34
35
36 ## Why Sass? {#why}
37
38 [Sass](https://sass-lang.com/) is the most widely used, feature rich, and stable CSS extension language available. It has become an essential tool in modern web development because of its ability to _reduce complexity_ and _increase composability_ when styling a website. For a basic example, suppose you want to use the same color for multiple styling rules in your website (e.g., hyperlinks and buttons). With CSS, you'd have to repeat that color every time it is used in styling rule, so in a large project, changing at a later point can be tedious and error-prone.
39
40 ```css
41 a {
42 color: salmon;
43 }
44 button {
45 background-color: salmon;
46 }
47 ```
48
49 With Sass, you could store this color in a Sass variable and use it in the styling rules to produce the same CSS, resulting in a single entry point for the color's value. This simple Sass tool can make CSS styling a lot easier to reason about, making styles a lot easier to customize and maintain.
50
51 ```css
52 $main-color: salmon;
53 a {
54 color: $main-color;
55 }
56 button {
57 background-color: $main-color;
58 }
59 ```
60
61 Sass variables are not the only Sass tool useful for reducing complexity. For Sass and **sass** newcomers, this vignette first covers how to use basic Sass tools like [variables](#variables), [mixins](#mixins), and [functions](#functions) in the **sass** R package. After the basics, you'll also learn how to write [composable **sass**](#layering) that allows users to easily override your styling defaults and developers to [include](#includes) your Sass in their styling projects. You'll also learn how to control the CSS output (e.g., [compress](#compression) and [cache](#caching) it), and how to use it in [**shiny**](#shiny) & [**rmarkdown**](#rmarkdown).
62
63 By mastering these concepts, you'll not only be able to leverage the advantages of using Sass over CSS, but you'll also have the basis needed to develop R interfaces to Sass projects that allow users to easily customize your styling templates _without any knowledge of Sass/CSS_. For an example, see the [**bslib** R package](https://github.com/rstudio/bslib), which provides a interface to [Bootstrap Sass](https://getbootstrap.com/docs/4.0/getting-started/theming/) through easy-to-use functions like `bs_theme_add_variables()`.
64
65 ## Sass Basics {#basics}
66
67 ```{r setup, include=FALSE}
68 library(sass)
69 knitr::opts_chunk$set(
70 collapse = TRUE,
71 message = FALSE,
72 fig.align = "center",
73 out.width = "80%",
74 class.output = "css",
75 comment = ""
76 )
77 ```
78
79 ### Variables {#variables}
80
81 [Sass variables](https://sass-lang.com/guide#topic-2) are a great mechanism for simplifying and exposing CSS logic to users. To create a variable, assign a value (likely a CSS [property value](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics)) to a name, then refer to it by name in downstream Sass code. In this minimal example, we create a `body-bg` variable then use it to generate a single [style rule](https://sass-lang.com/documentation//style-rules), but as we'll see later, variables can also be used inside of other arbitrary Sass code (e.g., functions, mixins, etc).
82
83 ```r
84 library(sass)
85 variable <- "$body-bg: red;"
86 rule <- "body { background-color: $body-bg; }"
87 sass(input = list(variable, rule))
88 ```
89
90 ```css
91 /* CSS */
92 body {
93 background-color: red;
94 }
95 ```
96
97 A more convenient and readable way to create Sass variables in R is to use a named `list()`. Also, it's a good idea to add the ` !default` flag after the value since it provides users of your Sass an opportunity to set their own value. We'll learn more about defaults in [layering](#layering), but for now, just note that the `!default` flag says use this value only if that variable isn't already defined:
98
99 ```r
100 user_default <- list("body-bg" = "blue !default")
101 default <- list("body-bg" = "red !default")
102 sass(input = list(user_default, default, rule))
103 ```
104
105 ```css
106 /* CSS */
107 body {
108 background-color: blue;
109 }
110 ```
111
112 ### Functions {#functions}
113
114 Sass comes with a variety of [built-in functions](https://sass-lang.com/documentation//modules) (i.e., you don't have to [import](#imports) anything to start using them) which are useful for working with CSS values ([colors](https://sass-lang.com/documentation//modules/color), [numbers](https://sass-lang.com/documentation//modules/math), [strings](https://sass-lang.com/documentation//modules/string), etc). These built-in functions are primarily useful modifying or combining CSS values in such a way that isn't possible with CSS. Here we use the `rgba()` to add alpha blending to `black` and assign the result to a variable.^[Oh, by the way, the value of a variable may be an expression.]
115
116 ```r
117 variable <- list("body-bg" = "rgba(black, 0.8)")
118 sass(input = list(variable, rule))
119 ```
120
121 ```css
122 /* CSS */
123 body {
124 background-color: rgba(0, 0, 0, 0.8);
125 }
126 ```
127
128 Sass also provides the ability to define your own functions through the [`@function` at-rule](https://sass-lang.com/documentation//at-rules/function). Like functions in most languages, there are four main components to a function definition: (1) the function `name`, (2) the function argument/inputs (e.g., `arg1`, `arg2`), (3) the function body which contains statements (i.e., `statement1`, `statement2`, etc.), and finally (4) a return `value`.
129
130 ```r
131 @function name(arg1, arg2) {
132 statement1;
133 statement2;
134 @return value;
135 }
136 ```
137
138 <br>
139
140 For an example of where creating your function becomes useful, consider this `color-contrast()` function, inspired by [this SO answer](https://stackoverflow.com/questions/3942878/how-to-decide-font-color-in-white-or-black-depending-on-background-color/3943023#3943023) to a common problem that arises when allowing users control over background color of something (e.g., the document body). We'd like to strive for styling rules that are smart enough to overlay white text on a dark colored background and black text on a light colored background. `color-contrast()` helps us achieve this since, given a dark color, it returns white; and given a light color, it returns black.
141
142 ```r
143 @function color-contrast($color) {
144 @return if(
145 red($color) * 0.299 + green($color) * 0.587 + blue($color) * 0.114 > 186,
146 black, white
147 );
148 }
149 ```
150
151 <br>
152
153 By saving this function to a file named `color-contrast.scss`, it can then be [imported](#imports) and used in the following way. For a live example of this in action, consider [this Shiny app](https://gallery.shinyapps.io/sass-font/) which allows the user to interactively choose a background color and the title's font color automatically updates to an appropriate color contrast. [See here](#shiny-dynamic) for more on allowing **shiny** users to influence styling on the page using **sass**.
154
155 ```r
156 sass(
157 list(
158 variable,
159 sass_file("color-contrast.scss"),
160 "body {
161 background-color: $body-bg;
162 color: color-contrast($body-bg);
163 }"
164 )
165 )
166 ```
167
168 ```css
169 /* CSS */
170 body {
171 background-color: rgba(0, 0, 0, 0.8);
172 color: white;
173 }
174 ```
175
176 **NOTE**: `bslib::bs_theme()` provides it's own, more sophisticated, version of `color-contrast()` that you can use like so: `sass::sass_partial("body{color: color-contrast($body-bg)}", bs_theme())`
177
178 ```{r, eval=FALSE, ref.label='bs_sass'}
179 ```
180
181 ### Importing {#imports}
182
183 In practice, you'll want to write your Sass code in `.scss` ([or `.sass`](https://sass-lang.com/documentation//syntax)) files (instead of inside R strings). That way you can leverage things like syntax highlighting in RStudio (or your favorite IDE) and make it easier for others to import your Sass into their workflow. For example, if I have `.scss` file in my working directory, say `my-style.scss`, I can compile it this way:
184
185 ```r
186 sass(sass_file("my-style.scss"))
187 ```
188
189 ```{r, echo = FALSE, out.width='50%'}
190 knitr::include_graphics('my-style.png')
191 ```
192
193 ```css
194 /* CSS */
195 body {
196 background-color: rgba(0, 0, 0, 0.8);
197 }
198 ```
199
200 This works because `sass_file()` uses `sass_import()` to generate an `@import` at-rule. If you visit the [docs for `@import`](https://sass-lang.com/documentation//at-rules/import), you'll notice there's more you can do that import local `.scss`, like import local or remote `.css` files, import font files, and more. Note also that `{sass}` also provides tools that make importing of local font files easier -- see `font_google()` to learn more.
201
202 ## Font imports {#file-import}
203
204 Importing font file(s) directly in Sass/CSS/HTML can be a headache to implement. This is especially true if you want to serve font files so that a custom font renders on any client machine, even if the client is without an internet connection. To make this easier, `{sass}` provides a `font_google()` which can be used to download, cache, import, and serve the relevant font files all at once.
205
206 ```r
207 library(htmltools)
208
209 my_font <- list("my-font" = font_google("Pacifico"))
210 css <- sass(
211 list(
212 my_font,
213 list("body {font-family: $my-font}")
214 )
215 )
216
217 shinyApp(
218 fluidPage(
219 "Hello",
220 tags$style(css)
221 ),
222 function(...) {}
223 )
224 ```
225
226 ```{r, echo = FALSE, out.width='30%'}
227 knitr::include_graphics('hello-pacifico.png')
228 ```
229
230 To import non-Google fonts, use either `font_link()` or `font_face()`. The former is for importing fonts via a remote URL whereas the former could be use to import any font locally (or remotely).
231
232 ### Mixins {#mixins}
233
234 Similar to how functions are useful for encapsulating _computation_ in a reusable unit, [mixins](https://sass-lang.com/documentation//at-rules/mixin) are useful for doing the same with _styling rules_ (i.e., packaging them into a reusable unit).
235 Technically speaking, mixins are similar to functions in that they require a `name`, may have arguments, as well as any number of statements. However, they differ in that they require the return value to be a [style rule](https://sass-lang.com/documentation//style-rules), and when called, need to be `@include`d in a larger style rule in order to generate any CSS.
236
237 For some examples, please see the [Sass mixin documentation](https://sass-lang.com/documentation//at-rules/mixin).
238
239 ### More basics
240
241 This vignette intentionally doesn't try to re-invent the existing and wonderful [Sass documentation](https://sass-lang.com/documentation/). There you'll find many more useful things as you start to write more Sass, such as [control flow](https://sass-lang.com/documentation//at-rules/control), [lists](https://sass-lang.com/documentation//values/lists), [maps](https://sass-lang.com/documentation//values/maps), [interpolation](https://sass-lang.com/documentation//interpolation), and more.
242
243 ## Composable sass {#layering}
244
245 To make Sass code more composable with other Sass code (e.g., allowing others to change your variable defaults or import a function or mixin you've defined), consider partitioning your Sass code into a `sass::sass_layer()`. The main idea is to split your Sass into 4 parts: [`functions`](#functions), `defaults` (i.e. [variable defaults](#variables)), [`mixins`](#mixins), and `rules` (i.e., styling rules).
246
247 ```r
248 layer1 <- sass_layer(
249 functions = sass_file("color-contrast.scss"),
250 defaults = list("body-bg" = "black !default"),
251 rules = "body{background-color: $body-bg; color: color-contrast($body-bg)}"
252 )
253 as_sass(layer1)
254 ```
255
256 ```css
257 /* CSS */
258 body {
259 background-color: black;
260 color: white;
261 }
262 ```
263
264 This allows downstream `sass_layer()`s to be `sass_bundle()`d into a single layer, where `defaults` in downstream layers are granted higher priority. More specifically, this means:
265
266 * `defaults` for `layer2` are placed _before_ `defaults` for `layer1`.
267 * Allowing downstream Sass to override variable defaults in upstream Sass.
268 * `rules` for `layer2` are placed _after_ `rules` for `layer1`.
269 * Allows downstream rules to take precedence over upstream rules ([precedence](https://css-tricks.com/precedence-css-order-css-matters/) matters when there are multiple rules with the same level of [specificity](https://css-tricks.com/specifics-on-css-specificity/)).
270
271 ```r
272 layer2 <- sass_layer(
273 defaults = list("body-bg" = "white !default")
274 )
275 sass(sass_bundle(layer1, layer2))
276 ```
277
278 ```css
279 /* CSS */
280 body {
281 background-color: white;
282 color: black;
283 }
284 ```
285
286 ### Resolving relative imports {#imports-relative}
287
288 Another problem that `sass_layer()` helps solve is that sometimes your Sass code might want to [import](#imports) a local file using a relative path that _you_ know how to resolve, but not necessarily the person who eventually compiles your Sass. To solve this issue, provide a named character vector to `file_attachments`, pointing the relevant relative path(s) to the appropriate absolute path(s). Here's a contrived example of how that might look ([here's](https://github.com/rstudio/bslib/blob/9c973e9/R/layers.R#L75-L77) a more real example of using it in an R package).
289
290 ```r
291 sass_layer(
292 declarations = "@import url('fonts/Source_Sans_Pro_300.ttf')",
293 file_attachments = c(
294 fonts = '/full/path/to/my/local/fonts'
295 )
296 )
297 ```
298
299 ### Attaching HTML dependencies {#html-dependencies}
300
301 Another problem that `sass_layer()` helps solve is that sometimes you want to attach other HTML dependencies to your Sass/CSS (e.g., JavaScript, other CSS, etc). For this reason, `sass_layer()` has a `html_deps` argument to which you can provide `htmltools::htmlDependency()` objects. `sass()` preserves these, as well as any other HTML dependencies attached to it's input, by including them in the return value. This ensures that, when you include `sass()` in [**rmarkdown**](#rmarkdown) or [**shiny**](#shiny-string) those dependencies come along for the ride.
302
303 **DISCLAIMER**: If you want to use this feature _and_ include [CSS as a file in shiny](#shiny-file), you'll need to call `htmltools::htmlDependencies()` on the return value of `sass()` to get the dependencies, then include them in your user interface definition.
304
305 ## CSS output options {#options}
306
307 The `sass()` function provides a few arguments for controlling the CSS output it generates, including `output`, `options`, and `cache_options`. The following covers some of the most important options available.
308
309 ### Output to a file {#output-file}
310
311 If the CSS generated from `sass()` can be useful in more than one place, consider writing it to a file (instead of returning it as a string). To write CSS to a file, give a suitable file path to `sass()`'s `output` argument.
312
313 ```r
314 sass(
315 sass_file("my-style.scss"),
316 output = "my-style.css"
317 )
318 ```
319
320 ### Compression {#compression}
321
322 By default, `sass()` outputs `'expanded'` CSS meaning there are lots of white-space and line-breaks included to make it more readable by humans. Computers don't need all those unnecessary characters, so to speed up your page load time when you go to include the CSS in [**shiny**](#shiny) or [**rmarkdown**](#rmarkdown), consider removing them altogether with `output_style = "compressed"`:
323
324 ```r
325 sass(
326 sass_file("my-style.scss"),
327 options = sass_options(output_style = "compressed")
328 )
329 ```
330
331 ### Source maps {#source-maps}
332
333 When compressing the CSS output, it can be useful to include a [source map](https://web.dev/articles/source-maps) so that it's easier to inspect the CSS from the website. The easiest way to include a source map is to set `source_map_embed = TRUE`:
334
335 ```r
336 sass(
337 sass_file("my-style.scss"),
338 options = sass_options(
339 output_style = "compressed",
340 source_map_embed = TRUE
341 )
342 )
343 ```
344
345 ### Caching {#caching}
346
347 Sometimes calling `sass()` can be computationally expensive, in which case, it can be useful to leverage its caching capability. Caching is enabled by default, unless Shiny's Developer Mode (`shiny::devmode()`) is enabled. To explicitly enable (disable), set `options(sass.cache = )` to `TRUE` (or `FALSE`):
348
349 ```r
350 withr::with_options(
351 list(sass.cache = TRUE),
352 sass(sass_file("my-style.scss"))
353 )
354 ```
355
356 You can also configure the location, size, and age of file caching via `sass_file_cache()`, which can be passed directly to a `sass()` call:
357
358 ```r
359 sass(
360 sass_file("my-style.scss"),
361 cache = sass_file_cache(getwd(), max_size = 100 * 1024^2)
362 )
363 ```
364
365 Or used with `sass_cache_set_dir()` to configure the file cache globally:
366
367 ```r
368 sass_cache_set_dir(getwd(), sass_file_cache(getwd(), max_size = 100 * 1024^2))
369 ```
370
371 Note that the location of the file cache defaults to `sass_cache_context_dir()`, which depends on the context in which it's running. When inside a Shiny app, the cache location is relative to the app's directory so the cache can persist and be shared across R processes. Otherwise, the context directory is a OS and package specific caching directory.
372
373 ## In shiny {#shiny}
374
375 There are two basic approaches to including the CSS that `sass()` returns as HTML
376 in your **shiny** app. If you're curious, the official [shiny article on CSS](https://shiny.rstudio.com/articles/css.html) has more details with a couple different approaches. Regardless of the approach, consider leveraging [compressing](#compression) and [caching](#caching) the CSS output to make your app faster to load.
377
378 ### As a string {#shiny-string}
379
380 The character string that `sass()` returns is already marked as `HTML()`^[Including [dynamic user input](#shiny-dynamic) directly as `HTML()`, especially with free form inputs like `textInput()`, is a security vulnerability. Avoid it if you can.], so to include it in your **shiny** app, wrap it in a `<style>` tag. It's not necessary to place this tag in the `<head>` of the document, but it's good practice:
381
382 ```r
383 library(shiny)
384 css <- sass(sass_file("my-style.scss"))
385 fluidPage(
386 tags$head(tags$style(css),
387 ...
388 )
389 ```
390
391 ### As a file {#shiny-file}
392
393 To write CSS to a file, give a suitable file path to `sass()`'s `output` argument. Here we write to a specially named `www/` subdirectory so that **shiny** will automatically make those file(s) available to the web app.
394
395 ```r
396 library(shiny)
397 sass(
398 sass_file("my-style.scss"),
399 output = "www/my-style.css"
400 )
401 fluidPage(
402 tags$head(
403 tags$link(href = "my-style.css", rel = "stylesheet", type = "text/css")
404 ),
405 ...
406 )
407 ```
408
409 ### As a dynamic input {#shiny-dynamic}
410
411 Sometimes it's useful to allow users of your **shiny** app to be able to influence your app's styling via **shiny** input(s). One way this can be done is via [dynamic UI](https://shiny.rstudio.com/articles/dynamic-ui.html), where you use `renderUI()`/`uiOutput()` to dynamically insert [CSS as an HTML string](#shiny-string) whenever a relevant input changes. Be aware, however, that whenever you allow dynamic user input to generate `HTML()`, you're leaving yourself open to security vulnerabilites; so try to avoid it, and _never_ allow clients to enter free form `textInput()` without any sort of sanitation of the user input.
412
413 Consider this basic example of using a `colourInput()` widget (from the **colourpicker** package) to choose the body's background color, which triggers a call to `sass()`:
414
415 ```r
416 library(shiny)
417
418 ui <- fluidPage(
419 headerPanel("Sass Color Example"),
420 colourpicker::colourInput("color", "Background Color", value = "#6498d2", showColour = "text"),
421 uiOutput("sass")
422 )
423
424 server <- function(input, output) {
425 output$sass <- renderUI({
426 tags$head(tags$style(css()))
427 })
428 css <- reactive({
429 sass::sass(list(
430 list(color = input$color),
431 "body { background-color: $color; }"
432 ))
433 })
434 }
435
436 shinyApp(ui, server)
437 ```
438
439 <br>
440
441 ```{r, echo = FALSE}
442 knitr::include_graphics("https://i.imgur.com/5cUEifg.gif")
443 ```
444
445
446 Below are a few more sophisticated examples of dynamic input:
447
448 * Font Color
449 * https://gallery.shinyapps.io/sass-font
450 * `shiny::runApp(system.file("sass-font", package = "sass"))`
451 * Sizing
452 * https://gallery.shinyapps.io/sass-size
453 * `shiny::runApp(system.file("sass-size", package = "sass"))`
454 * Themes
455 * https://gallery.shinyapps.io/sass-theme
456 * `shiny::runApp(system.file("sass-theme", package = "sass"))`
457
458
459 ## In rmarkdown {#rmarkdown}
460
461 **knitr** [recently gained](https://github.com/yihui/knitr/pull/1666) a Sass engine powered by the **sass** package. This means you can write Sass code directly into a code `sass` chunk and the resulting CSS will be included in the resulting document (The `echo = FALSE` prevents the Sass code from being shown in the resulting document).
462
463 ```{sass, echo = FALSE}`r ''`
464 $body-bg: red;
465 body{
466 background-color: $body-bg;
467 }
468 ```
469
470 If you like to write R **sass** code instead, you can do that as well, and by default it works similarly to the `sass` engine (except that the sass-specific code chunk options will be ignored, but you can specify those [options](#options) via `sass::sass()` instead).
471
472 ```{r, echo = FALSE}`r ''`
473 sass(sass_file("my-style.scss"))
474 ```
475
476 If syntax highlighting is enabled in your output document , it's also possible to display the generated CSS (instead of embedding it as HTML) with syntax highlighting by setting the code chunk options `class.output='css'` and `comment=''`. Unfortunately, for some output formats, like `rmarkdown::html_vignette()`, syntax hightlighting isn't supported, but for output formats like `rmarkdown::html_document()`, you can enable syntax highlighting by setting the `highlight` parameter to a non-default value (e.g., `tango`).
477
478 ```{r, class.output='css', comment=''}`r ''`
479 sass(sass_file("my-style.scss"))
480 ```