Debian Codegraph @

R/html_dependencies.R

raw
1 #' @importFrom htmltools htmlDependency copyDependencyToDir
2 #' makeDependencyRelative renderDependencies tagList tags
3 #' restorePreserveChunks extractPreserveChunks HTML
4 NULL
5
6 #' Provide common HTML dependencies for R Markdown formats
7 #'
8 #' These functions provide common HTML dependencies (e.g. jquery, bootstrap)
9 #' for re-use by other R Markdown formats.
10 #'
11 #' @inheritParams html_document
12 #' @name html-dependencies
13 NULL
14
15 # Create an HTML dependency for jQuery
16 #' @rdname html-dependencies
17 #' @export
18 html_dependency_jquery <- function() {
19 jquerylib::jquery_core(major_version = getOption('rmarkdown.jquery.version', 3))
20 }
21
22 # Create an HTML dependency for jQuery UI
23 #' @rdname html-dependencies
24 #' @export
25 html_dependency_jqueryui <- function() {
26
27 htmlDependency(
28 name = "jqueryui",
29 version = version_jqueryui,
30 src = pkg_file("rmd/h/jqueryui"),
31 script = "jquery-ui.min.js")
32 }
33
34 # Create an HTML dependency for Bootstrap
35 #' @rdname html-dependencies
36 #' @export
37 html_dependency_bootstrap <- function(theme) {
38 theme <- resolve_theme(theme)
39
40 # Bootstrap with bslib package
41 if (is_bs_theme(theme)) {
42 # TODO: would it make sense for these additional rules to come as a part of
43 # bslib::bs_theme_dependencies() (for consistency sake)?
44 h1_size <- if ("3" %in% theme_version(theme)) "font-size-h1" else "h1-font-size"
45 theme <- bslib::bs_add_rules(
46 theme, c(
47 paste0("h1.title {margin-top: 1.25rem; font-size: 1.15 * $", h1_size, "}"),
48 "pre:not([class]) { background-color: $body-bg }"
49 )
50 )
51 return(bslib::bs_theme_dependencies(theme))
52 }
53
54 # Rmarkdown own BS3 dependency
55 htmlDependency(
56 name = "bootstrap",
57 version = "3.3.5",
58 src = pkg_file("rmd/h/bootstrap"),
59 meta = list(viewport = "width=device-width, initial-scale=1"),
60 script = c(
61 "js/bootstrap.min.js",
62 # These shims are necessary for IE 8 compatibility
63 "shim/html5shiv.min.js",
64 "shim/respond.min.js"),
65 stylesheet = paste0("css/", theme, ".min.css"),
66 # CSS rules yanked from inst/rmd/h/default.html that should remain for historical
67 # reasons, but shouldn't be included if bslib is relevant
68 head = format(tags$style(HTML(
69 "h1 {font-size: 34px;}
70 h1.title {font-size: 38px;}
71 h2 {font-size: 30px;}
72 h3 {font-size: 24px;}
73 h4 {font-size: 18px;}
74 h5 {font-size: 16px;}
75 h6 {font-size: 12px;}
76 code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
77 pre:not([class]) { background-color: white }"
78 )))
79 )
80 }
81
82 bootstrap_dependencies <- function(theme) {
83 deps <- html_dependency_bootstrap(theme)
84 if (inherits(deps, "html_dependency")) list(deps) else deps
85 }
86
87 # resolves boostrap theme for bslib compatibility
88 resolve_theme <- function(theme) {
89 # theme = NULL means no Bootstrap
90 if (is.null(theme)) return(theme)
91
92 # Bootstrap/Bootswatch 3 names (backwards-compatibility)
93 if (is.character(theme)) {
94 if (length(theme) != 1) {
95 stop2("`theme` must be character vector of length 1.")
96 }
97 if (identical(theme, "default")) {
98 theme <- "bootstrap"
99 }
100
101 # special handling triggered when bootstrap folder removed from installation folder
102 # In this case, bslib is used as default.
103 bslib_forced_mode <- getOption("rmarkdown.bslib_forced_mode", FALSE)
104 if (bslib_forced_mode || !dir.exists(pkg_file("rmd/h/bootstrap"))) {
105 # we are in special bslib default mode, theme is tweaked to be a list
106 if (!is_available("bslib")) {
107 stop2(
108 "bslib package is required and must be installed",
109 if (bslib_forced_mode) " when in special bslib forced mode",
110 "."
111 )
112 }
113 return(bslib::bs_theme(version = 3, bootswatch = theme))
114 }
115
116 return(match.arg(theme, themes()))
117 }
118
119 # Bootstrap theme handled by bslib package
120 if (is.list(theme)) {
121 if (!is_available("bslib")) {
122 stop2("Providing a list to `theme` requires the bslib package.")
123 }
124 return(as_bs_theme(theme))
125 }
126 stop2(
127 "`theme` expects any one of the following values: \n",
128 " (1) NULL (no Bootstrap), \n",
129 " (2) a character string referencing a Bootswatch 3 theme name, \n",
130 " (3) a list of arguments to bslib::bs_theme(), \n",
131 " (4) a bslib::bs_theme() object."
132 )
133 }
134
135 # At the moment, theme may be either NULL (no Bootstrap), a string (Bootswatch
136 # 3 name), a bslib::bs_theme(), or a list of arguments to bs_theme().
137 as_bs_theme <- function(theme) {
138 if (is_bs_theme(theme)) {
139 return(theme)
140 }
141 if (is.list(theme)) {
142 return(do.call(bslib::bs_theme, theme))
143 }
144 NULL
145 }
146
147 is_bs_theme <- function(theme) {
148 is_available("bslib") &&
149 bslib::is_bs_theme(theme)
150 }
151
152 theme_version <- function(theme) {
153 if (is_bs_theme(theme)) return(bslib::theme_version(theme))
154 substr(html_dependency_bootstrap("default")$version, 1, 1)
155 }
156
157 needs_sass <- function(css) {
158 grepl("\\.s[ac]ss$", css)
159 }
160
161
162 # Create an HTML dependency for tocify
163 #' @rdname html-dependencies
164 #' @export
165 html_dependency_tocify <- function() {
166
167 htmlDependency(
168 name = "tocify",
169 version = "1.9.1",
170 src = pkg_file("rmd/h/tocify"),
171 script = "jquery.tocify.js",
172 stylesheet = "jquery.tocify.css")
173 }
174
175 # Create an HTML dependency for Pandoc code block accessibility
176 html_dependency_accessible_code_block <- function() {
177 ver <- pandoc_version()
178 if (ver < '2.7.3' || ver > '2.9.2.1') return()
179 htmlDependency(
180 name = "accessible-code-block",
181 version = "0.0.1",
182 src = pkg_file("rmd/h/accessibility"),
183 script = "empty-anchor.js"
184 )
185 }
186
187 # Create an HTML dependency for FontAwesome
188 #' @rdname html-dependencies
189 #' @export
190 html_dependency_font_awesome <- function() {
191 fontawesome::fa_html_dependency()
192 }
193
194 # Create an HTML dependency for Ionicons
195 #' @rdname html-dependencies
196 #' @export
197 html_dependency_ionicons <- function() {
198
199 htmlDependency(
200 name = "ionicons",
201 version = "2.0.1",
202 src = pkg_file("rmd/h/ionicons"),
203 stylesheet = "css/ionicons.min.css")
204 }
205
206 html_dependency_navigation <- function(code_menu, source_embed) {
207
208 # dynamically build script list
209 script <- c("tabsets.js")
210 if (code_menu)
211 script <- c(script, "codefolding.js")
212 if (source_embed)
213 script <- c(script, "sourceembed.js")
214
215 htmlDependency(name = "navigation",
216 version = "1.1",
217 src = pkg_file("rmd/h/navigation-1.1"),
218 script = script)
219 }
220
221 html_dependency_anchor_sections <- function(style = c("hash", "symbol", "icon"),
222 section_divs = FALSE) {
223 style <- match.arg(style)
224 # dynamically build css list
225 content_style <- function(style) sprintf("anchor-sections-%s.css", style)
226 htmlDependency(name = "anchor-sections",
227 version = "1.1.0",
228 src = pkg_file("rmd/h/anchor-sections"),
229 script = if (section_divs) "anchor-sections.js",
230 stylesheet = c("anchor-sections.css", content_style(style))
231 )
232 }
233
234 # analyze navbar html source for icon dependencies
235 navbar_icon_dependencies <- function(navbar) {
236
237 # read the navbar source
238 source <- read_utf8(navbar)
239
240 # find icon references
241 res <- regexec('<(span|i) +class *= *("|\') *(fa\\w? fa|ion ion)-', source)
242 matches <- regmatches(source, res)
243 libs <- c()
244 for (match in matches) {
245 if (length(match) > 0)
246 libs <- c(libs, match[[4]])
247 }
248 libs <- unique(libs)
249
250 # return their dependencies
251 any_fa <- any(grepl("fa\\w? fa", libs))
252 any_ion <- any(grepl("ion ion", libs))
253 html_dependencies_fonts(any_fa, any_ion)
254 }
255
256 # utility function to return a list of font dependencies based
257 # whether we are including font_awesome and/or ionicons
258 html_dependencies_fonts <- function(font_awesome, ionicons) {
259 deps <- list()
260 if (font_awesome)
261 deps <- append(deps, list(html_dependency_font_awesome()))
262 if (ionicons)
263 deps <- append(deps, list(html_dependency_ionicons()))
264 deps
265 }
266
267 # flattens an arbitrarily nested list and returns all of the dependency
268 # objects it contains
269 flatten_dependencies <- function(knit_meta, test) {
270
271 all_dependencies <- list()
272
273 # knit_meta is a list of 'meta' attributes returned from custom knit_print
274 # functions. since the 'meta' attribute could either be an html dependency or
275 # a list of dependencies we recurse on lists that aren't named
276 for (dep in knit_meta) {
277 if (is.null(names(dep)) && is.list(dep)) {
278 inner_dependencies <- flatten_dependencies(dep, test)
279 all_dependencies <- append(all_dependencies, inner_dependencies)
280 } else if (test(dep)) {
281 all_dependencies[[length(all_dependencies) + 1]] <- dep
282 }
283 }
284
285 all_dependencies
286 }
287
288 flatten_html_dependencies <- function(knit_meta) {
289 flatten_dependencies(knit_meta, is_html_dependency)
290 }
291
292 # consolidate dependencies (use latest versions and remove duplicates). this
293 # routine is the default implementation for version dependency resolution;
294 # formats may specify their own.
295 html_dependency_resolver <- function(all_dependencies) {
296
297 dependencies <- htmltools::resolveDependencies(all_dependencies)
298
299 # validate each surviving dependency
300 dependencies <- lapply(dependencies, validate_html_dependency)
301
302 # return the consolidated dependencies
303 dependencies
304 }
305
306 html_reference_path <- function(path, lib_dir, output_dir) {
307 # write the full OS-specific path if no library
308 if (is.null(lib_dir))
309 pandoc_path_arg(path)
310 else
311 relative_to(output_dir, path)
312 }
313
314 # return the html dependencies as an HTML string suitable for inclusion
315 # in the head of a document
316 html_dependencies_as_string <- function(dependencies, lib_dir, output_dir) {
317 if (!is.null(lib_dir)) {
318 # using mustWork=FALSE insures non-disk based dependencies are
319 # return untouched, keeping the order of all deps.
320 dependencies <- lapply(dependencies, copyDependencyToDir,
321 outputDir = lib_dir, mustWork = FALSE)
322 dependencies <- lapply(dependencies, makeDependencyRelative,
323 basepath = output_dir, mustWork = FALSE)
324 }
325
326 # Dependencies are iterated on as file based dependencies needs to be
327 # processed a specific way for Pandoc compatibility.
328 html <- c()
329 for (dep in dependencies) {
330 tags <- if (is.null(dep$src[["file"]])) {
331 renderDependencies(list(dep), "href")
332 } else {
333 renderDependencies(list(dep), "file",
334 encodeFunc = identity,
335 hrefFilter = function(path) {
336 html_reference_path(path, lib_dir, output_dir)
337 })
338 }
339 html <- c(html, tags)
340 }
341 HTML(paste(html, collapse = "\n"))
342 }
343
344 # check class of passed list for 'html_dependency'
345 is_html_dependency <- function(list) {
346 inherits(list, "html_dependency")
347 }
348
349 # validate that the passed list is a correctly formed html_dependency
350 validate_html_dependency <- function(list) {
351
352 # ensure it's the right class
353 if (!is_html_dependency(list))
354 stop2("passed object is not of class html_dependency")
355
356 # validate required fields
357 if (is.null(list$name))
358 stop2("name for html_dependency not provided")
359 if (is.null(list$version))
360 stop2("version for html_dependency not provided")
361 list <- fix_html_dependency(list)
362
363 # check src path or href are given
364 if (is.null(list$src)) {
365 stop2("src for html_dependency not provided")
366 }
367 if (!is.null(list$src$file)) {
368 file <- list$src$file
369 if (!is.null(list$package))
370 file <- system.file(file, package = list$package)
371 if (!file.exists(file)) {
372 stop2("path for html_dependency not found: ", file)
373 }
374 }
375
376 list
377 }
378
379 # monkey patch HTML dependencies; currently only supports highlight.js
380 fix_html_dependency <- function(list) {
381 if (!identical(list$name, 'highlightjs') || !identical(list$version, '1.1'))
382 return(list)
383 if (!identical(list$src$file, '')) return(list)
384 html_dependency_highlightjs(gsub('[.]css$', '', list$stylesheet))
385 }
386
387 # check if the passed knit_meta has any (e.g. html/latex) dependencies
388 has_dependencies <- function(knit_meta, class) {
389
390 if (inherits(knit_meta, class))
391 return(TRUE)
392
393 if (is.list(knit_meta)) {
394 for (dep in knit_meta) {
395 if (is.null(names(dep))) {
396 if (has_dependencies(dep, class))
397 return(TRUE)
398 } else {
399 if (inherits(dep, class))
400 return(TRUE)
401 }
402 }
403 }
404 FALSE
405 }
406
407 has_html_dependencies <- function(knit_meta) {
408 has_dependencies(knit_meta, "html_dependency")
409 }
410
411 # create an html_dependency for pagedtable
412 #' @rdname html-dependencies
413 #' @export
414 html_dependency_pagedtable <- function() {
415 htmlDependency(
416 "pagedtable",
417 version = "1.1",
418 src = pkg_file("rmd/h/pagedtable-1.1"),
419 script = "js/pagedtable.js",
420 stylesheet = "css/pagedtable.css"
421 )
422 }
423
424 #' @param highlight Highlighter to use
425 #' @rdname html-dependencies
426 #' @export
427 html_dependency_highlightjs <- function(highlight) {
428 htmlDependency(
429 "highlightjs",
430 version = "9.12.0",
431 src = pkg_file("rmd/h/highlightjs"),
432 script = "highlight.js",
433 stylesheet = paste0(highlight, ".css")
434 )
435 }
436
437 # create an html_dependency for rsiframe
438 html_dependency_rsiframe <- function() {
439
440 # add session port to meta if we have it (note that RStudio will
441 # only provide this in desktop mode)
442 meta <- NULL
443 session_port <- Sys.getenv("RSTUDIO_SESSION_PORT")
444 if (nzchar(session_port))
445 meta <- list(rstudio_origin = paste0("127.0.0.1:", session_port))
446
447 htmlDependency(
448 "rstudio-iframe",
449 version = "1.1",
450 src = pkg_file("rmd/h/rsiframe-1.1"),
451 script = "rsiframe.js",
452 meta = meta
453 )
454 }
455
456 # Pandoc 2.9 adds attributes on both headers and their parent divs. We remove
457 # the ones on headers since they are unnecessary (#1723).
458 html_dependency_header_attrs <- function() {
459 if (getOption('rmarkdown.html_dependency.header_attr', TRUE) && pandoc_available('2.9')) {
460 list(
461 htmlDependency(
462 "header-attrs",
463 version = packageVersion("rmarkdown"),
464 src = pkg_file("rmd/h/pandoc"),
465 script = "header-attrs.js"
466 )
467 )
468 }
469 }
470
471 # Store KaTeX as a html dependency to include in our template
472 html_dependency_katex <- function(href = NULL) {
473 # supporting custom url
474 if (is.null(href)) {
475 href <- "https://cdn.jsdelivr.net/npm/[email protected]/dist/"
476 version <- "0.15.2"
477 integrity <- "sha256-bgI9WhLOPSUlPrdgHUg3rPIB2vq+D+mYkUTM3q0U8fw="
478 } else {
479 # if a custom url is passed we can't set value we don't know
480 integrity <- NULL
481 # guessing version from a CDN
482 r <- "^.*katex@([0-9.]+).*"
483 version <- if (grepl(r, href)) {
484 gsub(r, "\\1", href)
485 } else {
486 "99.99.99"
487 }
488 }
489
490 htmlDependency(
491 name = "katex",
492 version = version,
493 src = c(href = href),
494 script = c(
495 list(src = "katex.min.js",
496 'data-external' = "1",
497 defer = NA),
498 if (!is.null(integrity)) {
499 list(integrity = integrity, crossorigin = 'anonymous')
500 }
501 ),
502 # TODO: reactivate when we can set data-external = 1 in htmltools
503 #
504 # stylesheet = c("katex.min.css"),
505 # from Pandoc
506 # https://github.com/jgm/pandoc/blob/7ddb609aae48ec10ef9899b25c52a4abecfbc176/src/Text/Pandoc/Writers/HTML.hs#L313
507 head = c(
508 '<script>document.addEventListener("DOMContentLoaded", function () {',
509 ' var mathElements = document.getElementsByClassName("math");',
510 ' var macros = [];',
511 ' for (var i = 0; i < mathElements.length; i++) {',
512 ' var texText = mathElements[i].firstChild;',
513 ' if (mathElements[i].tagName == "SPAN") {',
514 ' katex.render(texText.data, mathElements[i], {',
515 ' displayMode: mathElements[i].classList.contains("display"),',
516 ' throwOnError: false,',
517 ' macros: macros,',
518 ' fleqn: false',
519 ' });',
520 ' }}});',
521 '</script>',
522 sprintf('<link rel="stylesheet" href="%skatex.min.css" data-external="1">', href)
523 )
524 )
525 }
526
527 #' @rdname html-dependencies
528 #' @export
529 html_dependency_tabset <- function() {
530 htmlDependency(
531 "tabset",
532 version = "1.0",
533 src = pkg_file("rmd/h/tabset"),
534 script = "tabset.js",
535 stylesheet = "tabset.css",
536 all_files = FALSE
537 )
538 }
539
540 #' @rdname html-dependencies
541 #' @export
542 html_dependency_codefolding_lua <- function() {
543 htmlDependency(
544 "codefolding-lua",
545 version = "1.1",
546 src = pkg_file("rmd/h/navigation-1.1"),
547 stylesheet = "codefolding-lua.css",
548 all_files = FALSE
549 )
550 }