Debian Codegraph @

R/html_notebook_output.R

raw
1 #' Generate R Notebook Output
2 #'
3 #' Utilities for generating output for the \code{html_notebook} format,
4 #' through the \code{output_source} function attached to a
5 #' \code{\link{output_format}}.
6 #'
7 #' See the \href{https://rmarkdown.rstudio.com/r_notebook_format.html}{online
8 #' documentation} for additional details on using the \code{html_notebook}
9 #' format.
10 #' @param path A path to a file. For functions accepting both \code{path}
11 #' and \code{bytes}, if \code{bytes} is \code{NULL}, the bytewise contents
12 #' will be obtained by reading the file.
13 #' @param bytes The bytewise representation of content.
14 #' @param html Arbitrary HTML content to insert.
15 #' @param attributes A named \R list of HTML attributes. These will be
16 #' escaped and inserted into the generated HTML as appropriate.
17 #' @param code Source code.
18 #' @param meta An \R list of arbitrary meta-data. The data will
19 #' be converted to JSON, base64-encoded, and injected into the header comment.
20 #' @param format The image format; one of \code{"png"} or \code{"jpeg"}.
21 #' @name html_notebook_output
22 NULL
23
24 #' Generate R Notebook Metadata
25 #'
26 #' A structured helper for the construction of metadata used by the
27 #' R Notebook output functions. See \code{\link{html_notebook_output}} for
28 #' more details.
29 #' @param iframe Boolean; should output be shown in an \code{<iframe>}?
30 #' @export
31 html_notebook_metadata <- function(iframe = TRUE) {
32 list(iframe = iframe)
33 }
34
35 html_notebook_render_base64_data <- function(path = NULL,
36 bytes = NULL,
37 attributes = NULL,
38 format) {
39 # read (if necessary) and encode data
40 if (is.null(bytes))
41 bytes <- read_file(path, binary = TRUE)
42 encoded <- xfun::base64_encode(bytes)
43
44 # generate html attributes
45 sprintf(format, to_html_attributes(attributes), encoded)
46 }
47
48 #' @name html_notebook_output
49 #' @export
50 html_notebook_output_html <- function(html,
51 meta = NULL) {
52 html_notebook_annotated_output(one_string(html), "html", meta)
53 }
54
55 #' @name html_notebook_output
56 #' @export
57 html_notebook_output_img <- function(path = NULL,
58 bytes = NULL,
59 attributes = NULL,
60 meta = NULL,
61 format = c("png", "jpeg")) {
62 template <- paste0('<img%s src="data:image/', match.arg(format),
63 ';base64,%s" />')
64 html <- html_notebook_render_base64_data(path, bytes, attributes, template)
65 html_notebook_annotated_output(html, "plot", meta)
66 }
67
68 #' @name html_notebook_output
69 #' @export
70 html_notebook_output_png <- html_notebook_output_img
71
72 #' @name html_notebook_output
73 #' @export
74 html_notebook_output_code <- function(code,
75 attributes = list(class = "r"),
76 meta = NULL) {
77 # generate code
78 code <- sprintf("```%s\n%s\n```", attributes$class, one_string(code))
79
80 # update metadata
81 meta$data <- code
82
83 # render
84 html_notebook_annotated_output(code, "source", meta)
85 }