Debian Codegraph @

R/ornament.R

raw
1 #' Helper to define the contents of a pillar
2 #'
3 #' This function is useful if your data renders differently depending on the
4 #' available width. In this case, implement the [pillar_shaft()] method for your
5 #' class to return a subclass of "pillar_shaft" and have the [format()] method
6 #' for this subclass call `new_ornament()`. See the implementation of
7 #' `pillar_shaft.numeric()` and `format.pillar_shaft_decimal()` for an example.
8 #'
9 #' @param x A character vector with formatting,
10 #' can use ANYI styles e.g provided by the \pkg{cli} package.
11 #'
12 #' @param width An optional width of the resulting pillar, computed from `x` if
13 #' missing
14 #' @param align Alignment, one of `"left"` or `"right"`
15 #'
16 #' @export
17 #' @examples
18 #' new_ornament(c("abc", "de"), align = "right")
19 new_ornament <- function(x, width = NULL, align = NULL) {
20 if (is.null(width)) {
21 width <- get_max_extent(x)
22 }
23
24 ret <- structure(
25 x,
26 align = align,
27 class = "pillar_ornament"
28 )
29 ret <- set_width(ret, width)
30 ret
31 }
32
33 #' @export
34 print.pillar_ornament <- function(x, ...) {
35 writeLines(style_bold("<pillar_ornament>"))
36 writeLines(format(x, ...))
37 invisible(x)
38 }
39
40 #' @export
41 format.pillar_ornament <- function(x, width = NULL, ...) {
42 align <- attr(x, "align", exact = TRUE)
43 align(x, width = width %||% get_width(x), align = align)
44 }