Type: Package
Version: 0.4.9
Title: Syntactically Awesome Style Sheets ('Sass')
Description: An 'SCSS' compiler, powered by the 'LibSass' library. With this, R developers can use variables, inheritance, and functions to generate dynamic style sheets. The package uses the 'Sass CSS' extension language, which is stable, powerful, and CSS compatible.
License: MIT + file LICENSE
URL: https://rstudio.github.io/sass/, https://github.com/rstudio/sass
BugReports: https://github.com/rstudio/sass/issues
Encoding: UTF-8
RoxygenNote: 7.3.1
SystemRequirements: GNU make
Imports: fs (≥ 1.2.4), rlang (≥ 0.4.10), htmltools (≥ 0.5.1), R6, rappdirs
Suggests: testthat, knitr, rmarkdown, withr, shiny, curl
VignetteBuilder: knitr
Config/testthat/edition: 3
NeedsCompilation: yes
Packaged: 2024-03-15 21:58:01 UTC; cpsievert
Author: Joe Cheng [aut], Timothy Mastny [aut], Richard Iannone ORCID iD [aut], Barret Schloerke ORCID iD [aut], Carson Sievert ORCID iD [aut, cre], Christophe Dervieux ORCID iD [ctb], RStudio [cph, fnd], Sass Open Source Foundation [ctb, cph] (LibSass library), Greter Marcel [ctb, cph] (LibSass library), Mifsud Michael [ctb, cph] (LibSass library), Hampton Catlin [ctb, cph] (LibSass library), Natalie Weizenbaum [ctb, cph] (LibSass library), Chris Eppstein [ctb, cph] (LibSass library), Adams Joseph [ctb, cph] (json.cpp), Trifunovic Nemanja [ctb, cph] (utf8.h)
Maintainer: Carson Sievert <carson@rstudio.com>
Repository: CRAN
Date/Publication: 2024-03-15 22:30:02 UTC

Convert an R object into Sass code

Description

Converts multiple types of inputs to a single Sass input string for sass().

Usage

as_sass(input)

Arguments

input

Any of the following:

Value

a single character value to be supplied to sass().

References

https://sass-lang.com/documentation/at-rules/import

Examples

# Example of regular Sass input
as_sass("body { color: \"blue\"; }")

# There is support for adding variables
as_sass(
  list(
    list(color = "blue"),
   "body { color: $color; }"
   )
)


# Add a file name
someFile <- tempfile("variables")

# Overwrite color to red
write("$color: \"red\";", someFile)

input <-
  as_sass(
    list(
      list(color = "blue"),
      sass_file(someFile),
      "body { color: $color; }"
      )
   )

input

# The final body color is red
sass(input)


Sass Bundle to Single Sass Layer

Description

Converts a sass_bundle() to a single Sass layer object.

Usage

as_sass_layer(x)

Details

This is exported for internal use between packages and should not be used. Instead, please use sass_layer() or sass_bundle() to construct and manage your sass objects and sass() and as_sass() to convert your objects.


Create a file cache object

Description

Create a file cache object

Create a file cache object

Details

A file cache object is a key-file store that saves the values as files in a directory on disk. The objects are files on disk. They are stored and retrieved using the get_file(), get_content(), set_file(), and set_content() methods. Objects are automatically pruned from the cache according to the parameters max_size, max_age, max_n, and evict.

Cache pruning

Cache pruning occurs when set_file() or set_content() is called, or it can be invoked manually by calling prune().

The disk cache will throttle the pruning so that it does not happen on every call to set_file() or set_content(), because the filesystem operations for checking the status of files can be slow. Instead, it will prune once in every 20 calls to set_file() or set_content(), or if at least 5 seconds have elapsed since the last prune occurred, whichever is first. These parameters are currently not customizable, but may be in the future.

When a pruning occurs, if there are any objects that are older than max_age, they will be removed.

The max_size and max_n parameters are applied to the cache as a whole, in contrast to max_age, which is applied to each object individually.

If the number of objects in the cache exceeds max_n, then objects will be removed from the cache according to the eviction policy, which is set with the evict parameter. Objects will be removed so that the number of items is max_n.

If the size of the objects in the cache exceeds max_size, then objects will be removed from the cache. Objects will be removed from the cache so that the total size remains under max_size. Note that the size is calculated using the size of the files, not the size of disk space used by the files — these two values can differ because of files are stored in blocks on disk. For example, if the block size is 4096 bytes, then a file that is one byte in size will take 4096 bytes on disk.

Another time that objects can be removed from the cache is when get_file() or get_content() is called. If the target object is older than max_age, it will be removed and the cache will report it as a missing value.

Eviction policies

If max_n or max_size are used, then objects will be removed from the cache according to an eviction policy. The available eviction policies are:

"lru"

Least Recently Used. The least recently used objects will be removed. This uses the filesystem's mtime property. When "lru" is used, each time get_file() or get_content() is called, it will update the file's mtime.

"fifo"

First-in-first-out. The oldest objects will be removed.

Both of these policies use files' mtime. Note that some filesystems (notably FAT) have poor mtime resolution. (atime is not used because support for atime is worse than mtime.)

Sharing among multiple processes

The directory for a FileCache can be shared among multiple R processes. To do this, each R process should have a FileCache object that uses the same directory. Each FileCache will do pruning independently of the others, so if they have different pruning parameters, then one FileCache may remove cached objects before another FileCache would do so.

Even though it is possible for multiple processes to share a FileCache directory, this should not be done on networked file systems, because of slow performance of networked file systems can cause problems. If you need a high-performance shared cache, you can use one built on a database like Redis, SQLite, mySQL, or similar.

When multiple processes share a cache directory, there are some potential race conditions. For example, if your code calls exists(key) to check if an object is in the cache, and then call get_file(key), the object may be removed from the cache in between those two calls, and get_file(key) will throw an error. Instead of calling the two functions, it is better to simply call get_file(key), and use tryCatch() to handle the error that is thrown if the object is not in the cache. This effectively tests for existence and gets the object in one operation.

It is also possible for one processes to prune objects at the same time that another processes is trying to prune objects. If this happens, you may see a warning from file.remove() failing to remove a file that has already been deleted.

Methods

Public methods


Method new()

Create a FileCache object.

Usage
FileCache$new(
  dir = NULL,
  max_size = 40 * 1024^2,
  max_age = Inf,
  max_n = Inf,
  evict = c("lru", "fifo"),
  destroy_on_finalize = FALSE,
  logfile = NULL
)
Arguments
dir

Directory to store files for the cache. If NULL (the default) it will create and use a temporary directory.

max_size

Maximum size of the cache, in bytes. If the cache exceeds this size, cached objects will be removed according to the value of the evict. Use Inf for no size limit.

max_age

Maximum age of files in cache before they are evicted, in seconds. Use Inf for no age limit.

max_n

Maximum number of objects in the cache. If the number of objects exceeds this value, then cached objects will be removed according to the value of evict. Use Inf for no limit of number of items.

evict

The eviction policy to use to decide which objects are removed when a cache pruning occurs. Currently, "lru" and "fifo" are supported.

destroy_on_finalize

If TRUE, then when the FileCache object is garbage collected, the cache directory and all objects inside of it will be deleted from disk. If FALSE (the default), it will do nothing when finalized.

logfile

An optional filename or connection object to where logging information will be written. To log to the console, use stdout().


Method get_file()

Get the content associated with key, and save in a file named outfile.

Usage
FileCache$get_file(key, outfile, overwrite = TRUE)
Arguments
key

Key. Must be lowercase numbers and letters.

outfile

Name of output file. If NULL, return the content as

overwrite

If the output file already exists, should it be overwritten?

Returns

TRUE if the object is found in the cache and copying succeeds, FALSE otherwise.


Method get_content()

Get the content associated with key, and return as either string or a raw vector.

Usage
FileCache$get_content(key, mode = c("text", "raw"))
Arguments
key

Key. Must be lowercase numbers and letters.

mode

If "text", return the content as a UTF-8-encoded text string (a one element char vector). If "raw", return the content as a raw vector.

Returns

A character or raw vector if the object is found in the cache, NULL otherwise.


Method set_file()

Sets content associated with key, from a file named infile.

Usage
FileCache$set_file(key, infile)
Arguments
key

Key. Must be lowercase numbers and letters.

infile

Name of input file.

Returns

TRUE if copying the file into the cache succeeds, FALSE otherwise.


Method set_content()

Sets content associated with key, from a single-element vector.

Usage
FileCache$set_content(key, content)
Arguments
key

Key. Must be lowercase numbers and letters.

content

A character or raw vector. If it is a character vector, it will be written with UTF-8 encoding, with with elements collapsed with ⁠\\n⁠ (consistent across platforms).

Returns

TRUE if setting the content in the cache succeeds, FALSE otherwise.


Method exists()

Check if content associated with key exists in cache

Usage
FileCache$exists(key)
Arguments
key

Key. Must be lowercase numbers and letters.

Returns

TRUE if the object is in the cache, FALSE otherwise.


Method keys()

Get all keys

Usage
FileCache$keys()
Returns

A character vector of all keys currently in the cache.


Method remove()

Remove an object

Usage
FileCache$remove(key)
Arguments
key

Key. Must be lowercase numbers and letters.

Returns

TRUE if the object was found and successfully removed, FALSE otherwise.


Method reset()

Clear all objects from the cache.

Usage
FileCache$reset()

Method dir()

Returns the directory used for the cache.

Usage
FileCache$dir()

Method prune()

Prune the cache, using the parameters specified by max_size, max_age, max_n, and evict.

Usage
FileCache$prune()

Method size()

Return the number of items currently in the cache.

Usage
FileCache$size()

Method destroy()

Clears all objects in the cache, and removes the cache directory from disk.

Usage
FileCache$destroy()

Method is_destroyed()

Reports whether the cache has been destroyed.

Usage
FileCache$is_destroyed(throw = FALSE)
Arguments
throw

Should this function throw an error if the cache has been destroyed?


Method finalize()

A finalizer for the cache.

Usage
FileCache$finalize()

Method clone()

The objects of this class are cloneable with this method.

Usage
FileCache$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


Helpers for importing web fonts

Description

Include font file(s) when defining a Sass variable that represents a CSS font-family property.

Usage

font_google(
  family,
  local = TRUE,
  cache = sass_file_cache(sass_cache_context_dir()),
  wght = NULL,
  ital = NULL,
  display = c("swap", "auto", "block", "fallback", "optional")
)

font_link(family, href)

font_face(
  family,
  src,
  weight = NULL,
  style = NULL,
  display = c("swap", "auto", "block", "fallback", "optional"),
  stretch = NULL,
  variant = NULL,
  unicode_range = NULL
)

font_collection(..., default_flag = TRUE, quote = TRUE)

is_font_collection(x)

Arguments

family

A character string with a single font family name.

local

Whether or not download and bundle local (woff2) font files.

cache

A sass_file_cache() object (or, more generally, a file caching class with ⁠$get_file()⁠ and ⁠$set_file()⁠ methods). Set this argument to FALSE or NULL to disable caching.

wght

One of the following:

  • NULL, the default weight for the family.

  • A character string defining an axis range

  • A numeric vector of desired font weight(s).

ital

One of the following:

  • NULL, the default font-style for the family.

  • 0, meaning font-style: normal

  • 1, meaning font-style: italic

  • c(0, 1), meaning both normal and italic

display

A character vector for the font-display ⁠@font-face⁠ property.

href

A URL resource pointing to the font data.

src

A character vector for the src ⁠@font-face⁠ property. Beware that is character strings are taken verbatim, so careful quoting and/or URL encoding may be required.

weight

A character (or numeric) vector for the font-weight ⁠@font-face⁠ property.

style

A character vector for the font-style ⁠@font-face⁠ property.

stretch

A character vector for the font-stretch ⁠@font-face⁠ property.

variant

A character vector for the font-variant ⁠@font-face⁠ property.

unicode_range

A character vector for unicode-range ⁠@font-face⁠ property.

...

a collection of font_google(), font_link(), font_face(), and/or character vector(s) (i.e., family names to include in the CSS font-family properly). Family names are automatically quoted as necessary.

default_flag

whether or not to include a !default when converted to a Sass variable with as_sass().

quote

whether or not to attempt automatic quoting of family names.

x

test whether x is a font_collection(), font_google(), font_link(), or font_face() object.

Details

These helpers must be used the named list approach to variable definitions, for example:

list(
  list("font-variable" = font_google("Pacifico")),
  list("body{font-family: $font-variable}")
)

Value

a sass_layer() holding an htmltools::htmlDependency() which points to the font files.

Font fallbacks

By default, font_google() downloads, caches, and serves the relevant font file(s) locally. By locally serving files, there's a guarantee that the font can render in any client browser, even when the client doesn't have internet access. However, when importing font files remotely (i.e., font_google(..., local = FALSE) or font_link()), it's a good idea to provide fallback font(s) in case the remote link isn't working (e.g., maybe the end user doesn't have an internet connection). To provide fallback fonts, use font_collection(), for example:

pacifico <- font_google("Pacifico", local = FALSE)
as_sass(list(
  list("font-variable" = font_collection(pacifico, "system-ui")),
  list("body{font-family: $font-variable}")
))

Default flags

These font helpers encourage best practice of adding a !default to Sass variable definitions, but the flag may be removed via font_collection() if desired.

as_sass(list("font-variable" = pacifico))
#> $font-variable: Pacifico !default;
as_sass(list("font-variable" = font_collection(pacifico, default_flag = F)))
#> $font-variable: Pacifico;

Serving non-Google fonts locally

Non-Google fonts may also be served locally with font_face(), but it requires downloading font file(s) and pointing src to the right location on disk. If you want src to be a relative file path (you almost certainly do), then you'll need to mount that resource path using something like shiny::addResourcePath() (for a shiny app) or servr::httd() (for static HTML).

References

https://developers.google.com/fonts/docs/css2

https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face

https://developer.mozilla.org/en-US/docs/Learn/CSS/Styling_text/Web_fonts

Examples


library(htmltools)

my_font <- list("my-font" = font_google("Pacifico"))
hello <- tags$body(
  "Hello",
  tags$style(
    sass(
      list(
        my_font,
        list("body {font-family: $my-font}")
      )
    )
  )
)

if (interactive()) {
  browsable(hello)
}

# Three different yet equivalent ways of importing a remotely-hosted Google Font
a <- font_google("Crimson Pro", wght = "200..900", local = FALSE)
b <- font_link(
  "Crimson Pro",
  href = "https://fonts.googleapis.com/css2?family=Crimson+Pro:wght@200..900"
)
url <- "https://fonts.gstatic.com/s/crimsonpro/v13/q5uDsoa5M_tv7IihmnkabARboYF6CsKj.woff2"
c <- font_face(
  family = "Crimson Pro",
  style = "normal",
  weight = "200 900",
  src = paste0("url(", url, ") format('woff2')")
)

An intelligent (temporary) output file

Description

Intended for use with sass()'s output argument for temporary file generation that is cache and options aware. In particular, this ensures that new redundant file(s) aren't generated on a sass() cache hit, and that the file's extension is suitable for the sass_options()'s output_style.

Usage

output_template(
  basename = "sass",
  dirname = basename,
  fileext = NULL,
  path = tempdir()
)

Arguments

basename

a non-empty character string giving the outfile name (without the extension).

dirname

a non-empty character string giving the initial part of the directory name.

fileext

the output file extension. The default is ".min.css" for compressed and compact output styles; otherwise, its ".css".

path

the output file's root directory path.

Value

A function with two arguments: options and suffix. When called inside sass() with caching enabled, the caching key is supplied to suffix.

Examples

sass("body {color: red}", output = output_template())

func <- output_template(basename = "foo", dirname = "bar-")
func(suffix = "baz")


Compile Sass to CSS

Description

Compile Sass to CSS using LibSass.

Usage

sass(
  input = NULL,
  options = sass_options_get(),
  output = NULL,
  write_attachments = NA,
  cache = sass_cache_get(),
  cache_key_extra = NULL
)

Arguments

input

Any of the following:

options

Compiler sass_options().

output

Specifies path to output file for compiled CSS. May be a character string or output_template()

write_attachments

If the input contains sass_layer() objects that have file attachments, and output is not NULL, then copy the file attachments to the directory of output. (Defaults to NA, which merely emits a warning if file attachments are present, but does not write them to disk; the side-effect of writing extra files is subtle and potentially destructive, as files may be overwritten.)

cache

This can be a directory to use for the cache, a FileCache object created by sass_file_cache(), or FALSE or NULL for no caching.

cache_key_extra

additional information to considering when computing the cache key. This should include any information that could possibly influence the resulting CSS that isn't already captured by input. For example, if input contains something like "@import sass_file.scss" you may want to include the file.mtime() of sass_file.scss (or, perhaps, a packageVersion() if sass_file.scss is bundled with an R package).

Value

If output = NULL, the function returns a string value of the compiled CSS. If output is specified, the compiled CSS is written to a file and the filename is returned.

Caching

By default, caching is enabled, meaning that sass() avoids the possibly expensive re-compilation of CSS whenever the same options and input are requested. Unfortunately, in some cases, options and input alone aren't enough to determine whether new CSS output must be generated. For example, changes in local file imports that aren't captured through sass_file()/sass_import(), may lead to a false-positive cache hit. For this reason, developers are encouraged to capture such information in cache_key_extra (possibly with packageVersion('myPackage') if shipping Sass with a package), and users may want to disable caching altogether during local development by calling options(sass.cache=FALSE).

In some cases when developing and modifying .scss files, sass() might not detect changes, and keep using cached .css files instead of rebuilding them. To be safe, if you are developing a theme with sass, it's best to turn off caching by calling options(sass.cache=FALSE).

If caching is enabled, sass() will attempt to bypass the compilation process by reusing output from previous sass() calls that used equivalent inputs. This mechanism works by computing a cache key from each sass() call's input, option, and cache_key_extra arguments. If an object with that hash already exists within the cache directory, its contents are used instead of performing the compilation. If it does not exist, then compilation is performed and usual and the results are stored in the cache.

If a file that is included using sass_file() changes on disk (i.e. its last-modified time changes), its previous cache entries will effectively be invalidated (not removed from disk, but they'll no longer be matched). However, if a file imported using sass_file() itself imports other sass files using ⁠@import⁠, changes to those files are invisible to the cache and you can end up with stale results. To avoid this problem when developing sass code, it's best to disable caching with options(sass.cache=FALSE).

By default, the maximum size of the cache is 40 MB. If it grows past that size, the least-recently-used objects will be evicted from the cache to keep it under that size. Also by default, the maximum age of objects in the cache is one week. Older objects will be evicted from the cache.

To clear the default cache, call sass_cache_get()$reset().

See Also

https://sass-lang.com/guide

Examples

# Raw Sass input
sass("foo { margin: 122px * .3; }")

# List of inputs, including named variables
sass(list(
  list(width = "122px"),
  "foo { margin: $width * .3; }"
))

# Compile a .scss file
example_file <- system.file("examples/example-full.scss", package = "sass")
sass(sass_file(example_file))

# Import a file
tmp_file <- tempfile()
writeLines("foo { margin: $width * .3; }", tmp_file)
sass(list(
  list(width = "122px"),
  sass_file(tmp_file)
))

## Not run: 
# ======================
# Caching examples
# ======================
# Very slow to compile
fib_sass <- "@function fib($x) {
  @if $x <= 1 {
    @return $x
  }
  @return fib($x - 2) + fib($x - 1);
}

body {
  width: fib(27);
}"

# The first time this runs it will be very slow
system.time(sass(fib_sass))

# But on subsequent calls, it should be very fast
system.time(sass(fib_sass))

# sass() can be called with cache=NULL; it will be slow
system.time(sass(fib_sass, cache = NULL))

# Clear the cache
sass_cache_get()$reset()

## End(Not run)

## Not run: 
# Example of disabling cache by setting the default cache to NULL.

# Disable the default cache (save the original one first, so we can restore)
old_cache <- sass_cache_get()
sass_cache_set(NULL)
# Will be slow, because no cache
system.time(sass(fib_sass))

# Restore the original cache
sass_cache_set(old_cache)

## End(Not run)

Return the cache directory for the current context.

Description

Return the cache directory for the current context.

Usage

sass_cache_context_dir()

Details

In most cases, this function returns the user's cache directory, by calling tools::R_user_dir("sass", which = "cache") (for R 4.0 and above) or rappdirs::user_cache_dir("R-sass") (for older versions of R).

If this function is called from a Shiny application, it will also look for a subdirectory named ⁠app_cache/⁠. If it exists, it will use a directory named ⁠app_cache/sass/⁠ to store the cache.

When running a Shiny application in a typical R session, it will not create the ⁠app_cache/⁠ subdirectory, but it will use it if present. This scopes the cache to the application.

With Shiny applications hosted on Shiny Server and Connect, it will create a ⁠app_cache/sass/⁠ subdirectory, so that the cache is scoped to the application and will not interfere with another application's cache.


Retrieve the default file cache

Description

When caching is enabled, this function returns a sass_file_cache() object that sass()'s cache argument uses (by default) for caching Sass compilation. When caching is disabled (either by setting the sass.cache option to FALSE, NULL, or via shiny::devmode()), this function returns NULL (effectively telling sass() to not cache by default).

Usage

sass_cache_get()

Details

When caching is enabled, then this function returns a sass_file_cache() object that (by default) uses sass_cache_context_dir() for its directory. The directory can also be customized by providing the sass.cache option with either a filepath (as a string) or a full-blown sass_file_cache() object.

See Also

sass_cache_get_dir(), sass()


Get and set the cache object registered for a specific directory

Description

Get and set the cache object registered for a specific directory

Usage

sass_cache_get_dir(dir, create = FALSE)

sass_cache_set_dir(dir, cache)

Arguments

dir

A directory. An error will be thrown if the directory does not exist.

create

If TRUE, then if the cache directory doesn't exist, or if there is not a registered cache object for the directory, create them as needed.

cache

A sass_file_cache() object, or NULL if you don't want to unset the cache for a directory.

Details

If sass_cache_get_dir() is called for a given directory, before sass_cache_set_dir() has been called for that directory, then it will return NULL.

After sass_cache_set_dir() is called for a directory, any future calls to sass_cache_get_dir() with that directory will return that specific cache object. This can be useful if you customize parameters for the cache object, like maximum size or age.

See Also

sass_cache_get(), sass_file_cache(), sass()


Caching Options for Sass (defunct)

Description

This function is no longer used. Please see sass_cache_get().

Usage

sass_cache_options(cache, cache_dir)

Arguments

cache

No longer used.

cache_dir

No longer used.


Create a file cache object

Description

This creates a file cache which is to be used by sass for caching generated .css files.

Usage

sass_file_cache(dir, max_size = 40 * 1024^2, max_age = Inf)

Arguments

dir

The directory in which to store the cached files.

max_size

The maximum size of the cache, in bytes. If the cache grows past this size, the least-recently-used objects will be removed until it fits within this size.

max_age

The maximum age of objects in the cache, in seconds. The default is one week.

Value

A FileCache object.

See Also

sass_cache_get(), sass_cache_context_dir(), FileCache

Examples

## Not run: 
# Create a cache with the default settings
cache <- sass_file_cache(sass_cache_context_dir())

# Clear the cache
cache$reset()

## End(Not run)


Sass Import

Description

Create an import statement to be used within your Sass file. See https://sass-lang.com/documentation/at-rules/import for more details.

Usage

sass_import(input, quote = TRUE)

sass_file(input)

Arguments

input

Character string to be placed in an import statement.

quote

Logical that determines if a double quote is added to the import value. Defaults to TRUE.

Details

sass_file() adds extra checks to make sure an appropriate file path exists given the input value.

Note that the LibSass compiler expects .sass files to use the Sass Indented Syntax.

Value

Fully defined Sass import string.

Examples

sass_import("foo")
sass_import("$foo", FALSE)

tmp_scss_file <- tempfile(fileext = ".scss")
writeLines("$color: red; body{ color: $color; }", tmp_scss_file)
sass_file(tmp_scss_file)
sass(sass_file(tmp_scss_file))


Bundling Sass layers

Description

Sass layers provide a way to package Sass variables, rules, functions, and mixins in a structured and composable way that follows best Sass practices. Most importantly, when multiple sass_layer() are combined into a sass_bundle(), variable defaults for later layers are placed before earlier layers, effectively 'new' defaults through all the 'old' defaults.

Usage

sass_layer(
  functions = NULL,
  defaults = NULL,
  mixins = NULL,
  rules = NULL,
  html_deps = NULL,
  file_attachments = character(0),
  declarations = NULL,
  tags = NULL
)

sass_layer_file(file)

sass_bundle(...)

sass_bundle_remove(bundle, name)

is_sass_bundle(x)

Arguments

functions

as_sass() input intended for Sass functions. Functions are placed before defaults so that variable definitions may make use of functions.

defaults

as_sass() input intended for variable defaults. These variable defaults after placed after functions but before mixins. When multiple layers are combined in a sass_bundle(), defaults are merged in reverse order; that is, sass_bundle(layer1, layer2) will include layer2$defaults before layer1$defaults.

mixins

as_sass() input intended for Sass mixins. Mixins are placed after defaults, but before rules.

rules

as_sass() input intended for Sass rules. Rules are placed last (i.e., after functions, defaults, and mixins).

html_deps

An HTML dependency (or a list of them). This dependency gets attached to the return value of sass()/as_sass().

file_attachments

A named character vector, representing file assets that are referenced (using relative paths) from the sass in this layer. The vector names should be a relative path, and the corresponding vector values should be absolute paths to files or directories that exist; at render time, each value will be copied to the relative path indicated by its name. (For directories, the contents of the source directory will be copied into the destination directory; the directory itself will not be copied.) You can also omit the name, in which case that file or directory will be copied directly into the output directory.

declarations

Deprecated, use functions or mixins instead.

tags

Deprecated. Preserve meta information using a key in sass_bundle(KEY = val). preserve simple metadata as layers are merged.

file

file path to a .scss file.

...

A collection of sass_layer()s and/or objects that as_sass() understands. Arguments should be provided in reverse priority order: defaults, declarations, and rules in later layers will take precedence over those of previous layers. Non-layer values will be converted to layers by calling sass_layer(rules = ...).

bundle

Output value from sass_layer() or sass_bundle()

name

If a Sass layer name is contained in name, the matching Sass layer will be removed from the bundle

x

object to inspect

Functions

Examples

blue <- list(color = "blue !default")
red <- list(color = "red !default")
green <- list(color = "green !default")

# a sass_layer() by itself is not very useful, it just defines some
# SASS to place before (defaults) and after (rules)
core <- sass_layer(defaults = blue, rules = "body { color: $color; }")
core
sass(core)

# However, by stacking sass_layer()s, we have ability to place
# SASS both before and after some other sass (e.g., core)
# Here we place a red default _before_ the blue default and export the
# color SASS variable as a CSS variable _after_ the core
red_layer <- sass_layer(red, rules = ":root{ --color: #{$color}; }")
sass(sass_bundle(core, red_layer))
sass(sass_bundle(core, red_layer, sass_layer(green)))

# Example of merging layers and removing a layer
# Remember to name the layers that are removable
core_layers <- sass_bundle(core, red = red_layer, green = sass_layer(green))
core_layers # pretty printed for console
core_slim <- sass_bundle_remove(core_layers, "red")
sass(core_slim)


# File attachment example: Create a checkboard pattern .png, then
# use it from a sass layer

tmp_png <- tempfile(fileext = ".png")
grDevices::png(filename = tmp_png, width = 20, height = 20,
  bg = "transparent", antialias = "none")
par(mar = rep_len(0,4), xaxs = "i", yaxs = "i")
plot.new()
rect(c(0,0.5), c(0,0.5), c(0.5,1), c(0.5,1), col = "#00000044", border=NA)
dev.off()

layer <- sass_layer(
  rules = ".bg-check { background-image: url(images/demo_checkboard_bg.png) }",
  file_attachments = c("images/demo_checkboard_bg.png" = tmp_png)
)

output_path <- tempfile(fileext = ".css")
sass(layer, output = output_path, write_attachments = TRUE)

Compiler Options for Sass

Description

Specify compiler options for sass(). To customize options, either provide sass_options() directly to a sass() call or set options globally via sass_options_set(). When shiny::devmode() is enabled, sass_options_get() defaults source_map_embed and source_map_contents to TRUE.

Usage

sass_options(
  precision = 5,
  output_style = "expanded",
  indented_syntax = FALSE,
  include_path = "",
  source_comments = FALSE,
  indent_type = "space",
  indent_width = 2,
  linefeed = "lf",
  output_path = "",
  source_map_file = "",
  source_map_root = "",
  source_map_embed = FALSE,
  source_map_contents = FALSE,
  omit_source_map_url = FALSE
)

sass_options_get(...)

sass_options_set(...)

Arguments

precision

Number of decimal places.

output_style

Bracketing and formatting style of the CSS output. Possible styles: "nested", "expanded", "compact", and "compressed".

indented_syntax

Enables the compiler to parse Sass Indented Syntax in strings. Note that the compiler automatically overrides this option to TRUE or FALSE for files with .sass and .scss file extensions respectively.

include_path

Vector of paths used to resolve ⁠@import⁠. Multiple paths are possible using a character vector of paths.

source_comments

Annotates CSS output with line and file comments from Sass file for debugging.

indent_type

Specifies the indent type as "space" or "tab".

indent_width

Number of tabs or spaces used for indentation. Maximum 10.

linefeed

Specifies how new lines should be delimited. Possible values: "lf", "cr", "lfcr", and "crlf".

output_path

Specifies the location of the output file. Note: this option will not write the file on disk. It is only for internal reference with the source map.

source_map_file

Specifies the location for Sass to write the source map.

source_map_root

Value will be included as source root in the source map information.

source_map_embed

Embeds the source map as a data URI.

source_map_contents

Includes the contents in the source map information.

omit_source_map_url

Disable the inclusion of source map information in the output file. Note: must specify output_path when TRUE.

...

arguments to sass_options(). For sass_options_set(), the following values are also acceptable:

  • NULL, clearing the global options.

  • Return value of sass_options_get().

  • Return value of sass_options_set().

Value

List of Sass compiler options to be used with sass(). For sass_options_set(), any previously set global options are returned.

Examples


x <- "foo { margin: 122px * .001; }"
sass(x)

# Provide options directly to sass()
sass(x, options = sass_options(precision = 1, output_style = "compact"))

# Or set some option(s) globally
old_options <- sass_options_set(precision = 1)
sass(x)

# Specify local options  while also respecting global options
sass(x, options = sass_options_get(output_style = "compact"))

# Restore original state
sass_options_set(old_options)


Compile rules against a Sass Bundle or Sass Layer object

Description

Replaces the rules for a sass_layer() object with new rules, and compile it. This is useful when (for example) you want to compile a set of rules using variables derived from a theme, but you do not want the resulting CSS for the entire theme – just the CSS for the specific rules passed in.

Usage

sass_partial(
  rules,
  bundle,
  options = sass_options_get(),
  output = NULL,
  write_attachments = NA,
  cache = sass_cache_get(),
  cache_key_extra = NULL
)

Arguments

rules

A set of sass rules, which will be used instead of the rules from layer.

bundle

A sass_bundle() or sass_layer() object.

options

Compiler sass_options().

output

Specifies path to output file for compiled CSS. May be a character string or output_template()

write_attachments

If the input contains sass_layer() objects that have file attachments, and output is not NULL, then copy the file attachments to the directory of output. (Defaults to NA, which merely emits a warning if file attachments are present, but does not write them to disk; the side-effect of writing extra files is subtle and potentially destructive, as files may be overwritten.)

cache

This can be a directory to use for the cache, a FileCache object created by sass_file_cache(), or FALSE or NULL for no caching.

cache_key_extra

additional information to considering when computing the cache key. This should include any information that could possibly influence the resulting CSS that isn't already captured by input. For example, if input contains something like "@import sass_file.scss" you may want to include the file.mtime() of sass_file.scss (or, perhaps, a packageVersion() if sass_file.scss is bundled with an R package).

Examples

theme <- sass_layer(
  defaults = sass_file(system.file("examples/variables.scss", package = "sass")),
  rules = sass_file(system.file("examples/rules.scss", package = "sass"))
)

# Compile the theme
sass(theme)

# Sometimes we want to use the variables from the theme to compile other sass
my_rules <- ".someclass { background-color: $bg; color: $fg; }"
sass_partial(my_rules, theme)


Deprecated

Description

Deprecated Sass functions

Usage

sass_layer_merge(...)

Functions


Write file attachments from a sass theme object

Description

Write file attachments from a sass theme object

Usage

write_file_attachments(file_attachments, output_path)

Arguments

file_attachments

A character vector of files or directories.

output_path

A directory to copy the attachments to.