Debian Codegraph @

R/shiny.R

raw
1 #' Run a Shiny document
2 #'
3 #' Start a Shiny server for the given document, and render it for display.
4 #'
5 #' The \code{run} function runs a Shiny document by starting a Shiny
6 #' server associated with the document. The \code{shiny_args} parameter can be
7 #' used to configure the server; see the \code{\link[shiny:runApp]{runApp}}
8 #' documentation for details.
9 #'
10 #' Once the server is started, the document will be rendered using
11 #' \code{\link{render}}. The server will initiate a render of the document
12 #' whenever necessary, so it is not necessary to call \code{run} every time
13 #' the document changes: if \code{auto_reload} is \code{TRUE}, saving the
14 #' document will trigger a render. You can also manually trigger a render by
15 #' reloading the document in a Web browser.
16 #'
17 #' The server will render any R Markdown (\code{.Rmd}) document in \code{dir};
18 #' the \code{file} argument specifies only the initial document to be
19 #' rendered and viewed. You can therefore link to other documents in the
20 #' directory using standard Markdown syntax, e.g.
21 #' \code{[Analysis Page 2](page2.Rmd)}.
22 #'
23 #' If \code{default_file} is not specified, nor is a file specified on the
24 #' URL, then the default document to serve at \code{/} is chosen from (in
25 #' order of preference):
26 #' \itemize{
27 #' \item{If \code{dir} contains only one \code{Rmd}, that \code{Rmd}.}
28 #' \item{The file \file{index.Rmd}, if it exists in \code{dir}.}
29 #' \item{The first \code{Rmd} that has \code{runtime: shiny} in its YAML metadata.}
30 #' \item{The file \file{index.html} (or \file{index.htm}), if it exists in \code{dir}.}
31 #' }
32 #'
33 #' If you wish to share R code between your documents, place it in a file
34 #' named \code{global.R} in \code{dir}; it will be sourced into the global
35 #' environment.
36 #' @param file Path to the R Markdown document to launch in a web browser.
37 #' Defaults to \code{index.Rmd} in the current working directory, but may be
38 #' \code{NULL} to skip launching a browser.
39 #' @param dir The directory from which to to read input documents. Defaults to
40 #' the parent directory of \code{file}.
41 #' @param default_file The file to serve at the Shiny server's root URL. If
42 #' \code{NULL} (the default), a sensible default is chosen (see Details)
43 #' @param auto_reload If \code{TRUE} (the default), automatically reload the
44 #' Shiny application when the file currently being viewed is changed on disk.
45 #' @param shiny_args Additional arguments to \code{\link[shiny:runApp]{runApp}}.
46 #' @param render_args Additional arguments to \code{\link{render}}.
47 #' @return Invisible NULL.
48 #' @note Unlike \code{\link{render}}, \code{run} does not render the document to
49 #' a file on disk. In most cases a Web browser will be started automatically
50 #' to view the document; see \code{launch.browser} in the
51 #' \code{\link[shiny:runApp]{runApp}} documentation for details.
52 #'
53 #' When using an external web browser with the server, specify the name of the
54 #' R Markdown file to view in the URL (e.g.
55 #' \code{http://127.0.0.1:1234/foo.Rmd}). A URL without a filename will show
56 #' the \code{default_file} as described above.
57 #' @examples
58 #' \dontrun{
59 #' # Run the Shiny document "index.Rmd" in the current directory
60 #' rmarkdown::run()
61 #'
62 #' # Run the Shiny document "shiny_doc.Rmd" on port 8241
63 #' rmarkdown::run("shiny_doc.Rmd", shiny_args = list(port = 8241))
64 #' }
65 #' @export
66 run <- function(file = "index.Rmd", dir = dirname(file), default_file = NULL,
67 auto_reload = TRUE, shiny_args = NULL, render_args = NULL) {
68
69 # if file is missing and there is an index.qmd (and no index.Rmd) then use that
70 if (missing(file) && !file.exists("index.Rmd") && file.exists("index.qmd"))
71 file <- "index.qmd"
72
73 # if the file argument is missing then substitute ui.Rmd if it exists
74 # (and index.Rmd does not exist)
75 if (missing(file) && missing(default_file)) {
76 if (!any(file.exists(file.path(dir, paste0("index.", c("qmd", "Rmd"))))) &&
77 any(file.exists(file.path(dir, paste0("ui.", c("qmd", "Rmd")))))) {
78 uiRmd = file.path(dir, "ui.Rmd")
79 file <- ifelse(file.exists(uiRmd), uiRmd, file.path(dir, "ui.qmd"))
80 }
81 }
82
83 # select the document to serve at the root URL if not user-specified. We exclude
84 # documents which start with a leading underscore (same pattern is used to
85 # designate "sub-documents" in R Markdown websites and bookdown)
86 if (is.null(default_file)) {
87 allRmds <- list.files(path = dir, pattern = "^[^_].*\\.[Rrq][Mm][Dd]$")
88 if (length(allRmds) == 1) {
89 # just one R Markdown document
90 default_file <- allRmds
91 } else {
92 # more than one: look for an index or ui
93 index <- which(tolower(allRmds) %in% c("index.rmd", "index.qmd", "ui.rmd", "ui.qmd"))
94 if (length(index) > 0) {
95 default_file <- allRmds[index[1]]
96 } else {
97 # look for first one that has runtime: shiny
98 for (rmd in allRmds) {
99 yaml <- yaml_front_matter(file.path(dir, rmd))
100 if (is_shiny(yaml$runtime, yaml$server)) {
101 default_file <- rmd
102 break
103 }
104 }
105 }
106 }
107 }
108
109 if (is.null(default_file)) {
110 # no R Markdown default found; how about an HTML?
111 indexHtml <- list.files(dir, "(index|ui).html?", ignore.case = TRUE)
112 if (length(indexHtml) > 0) default_file <- indexHtml[1]
113 }
114
115 # form and test locations
116 dir <- normalize_path(dir)
117 if (!dir_exists(dir)) stop("The directory '", dir, "' does not exist")
118
119 if (!is.null(file)) {
120 # compute file path relative to directory (remove common directory prefix
121 # if it exists)
122 file_rel <- normalize_path(file)
123 if (identical(substr(file_rel, 1, nchar(dir)), dir))
124 file_rel <- substr(file_rel, nchar(dir) + 2, nchar(file_rel))
125
126 # if we don't have a default to launch, make sure the user-specified file
127 # exists
128 if (is.null(default_file)) {
129 resolved <- resolve_relative(dir, file_rel)
130 if (is.null(resolved) || !file.exists(resolved))
131 stop("The file '", file, "' does not exist in the directory '", dir, "'")
132 }
133 }
134
135 if (is.null(render_args$envir)) render_args$envir <- parent.frame()
136
137 # determine the runtime of the target file
138 target_file <- file %||% file.path(dir, default_file)
139 yaml_front <- if (length(target_file)) yaml_front_matter(target_file)
140 runtime <- yaml_front$runtime
141 server <- yaml_front$server
142 theme <- render_args$output_options$theme
143 # Let shiny::getCurrentTheme() know about the yaml's theme, so
144 # things like `bslib::bs_themer()` can work with prerendered documents.
145 # Also note that we add the actual shiny::bootstrapLib() dependency
146 # inside the document's pre-processing hook so the 'last' version of
147 # the theme wins out
148 if (length(target_file)) {
149 format <- output_format_from_yaml_front_matter(read_utf8(target_file))
150 old_theme <- shiny::getCurrentTheme()
151 on.exit(set_current_theme(old_theme), add = TRUE)
152 set_current_theme(resolve_theme(format$options$theme))
153 }
154
155 # run using the requested mode
156 if (is_shiny_prerendered(runtime, server)) {
157
158 # get the pre-rendered shiny app
159 app <- shiny_prerendered_app(target_file, render_args = render_args)
160 } else {
161
162 # add rmd_resources handler on start
163 onStart <- function() {
164 global_r <- file.path.ci(dir, "global.R")
165 if (file.exists(global_r)) {
166 source(global_r, local = FALSE)
167 }
168 shiny::addResourcePath("rmd_resources", pkg_file("rmd/h/rmarkdown"))
169 }
170
171 # combine the user-supplied list of Shiny arguments with our own and start
172 # the Shiny server; handle requests for the root (/) and any R markdown files
173 # within
174 app <- shiny::shinyApp(ui = rmarkdown_shiny_ui(dir, default_file),
175 uiPattern = "^/$|^/index\\.html?$|^(/.*\\.[Rrq][Mm][Dd])$",
176 onStart = onStart,
177 server = rmarkdown_shiny_server(
178 dir, default_file, auto_reload, render_args))
179
180 # cleanup evaluated cache when the current shiny app exits
181 on.exit({
182 .globals$evaluated_global_chunks <- character()
183 }, add = TRUE)
184 }
185
186 # launch the app and open a browser to the requested page, if one was
187 # specified
188 launch_browser <- shiny_args$launch.browser %||% (!is.null(file) && interactive())
189 if (isTRUE(launch_browser)) {
190 launch_browser <- function(url) {
191 url <- paste(url, file_rel, sep = "/")
192 browser <- getOption("shiny.launch.browser")
193 if (is.function(browser)) {
194 browser(url)
195 } else {
196 utils::browseURL(url)
197 }
198 }
199 }
200
201 shiny_args <- merge_lists(list(appDir = app, launch.browser = launch_browser),
202 shiny_args)
203 ret <- do.call(shiny::runApp, shiny_args)
204 invisible(ret)
205 }
206
207 # create the Shiny server function
208 rmarkdown_shiny_server <- function(dir, file, auto_reload, render_args) {
209 function(input, output, session) {
210 path_info <- utils::URLdecode(session$request$PATH_INFO)
211 # strip /websocket/ from the end of the request path if present
212 path_info <- sub("/websocket/$", "", path_info)
213 if (path_info == "") path_info <- file
214
215 file <- resolve_relative(dir, path_info)
216 reactive_file <- if (auto_reload)
217 shiny::reactiveFileReader(500, session, file, identity)
218 else
219 function() { file }
220
221 envir_global <- render_args[['envir']]
222 envir_server <- list2env(list(
223 input = input, output = output, session = session
224 ), parent = envir_global)
225 render_args$envir <- new.env(parent = envir_server)
226
227 # when the file loads (or is changed), render to a temporary file, and
228 # read the contents into a reactive value
229 doc <- shiny::reactive({
230 # check to see whether we have cached output for this file
231 out <- rmd_cached_output(file)
232 output_dest <- out$dest
233
234 # if output is cached, return it directly
235 if (out$cached) {
236 if (nchar(out$resource_folder) > 0) {
237 shiny::addResourcePath(basename(out$resource_folder),
238 out$resource_folder)
239 }
240 return(out$shiny_html)
241 }
242
243 # ensure destination directory exists
244 if (!file.exists(dirname(output_dest))) {
245 dir.create(dirname(output_dest), recursive = TRUE, mode = "0700")
246 }
247
248 # check to see if the output already exists
249 resource_folder <- knitr_files_dir(output_dest)
250
251 # clear out performance timings
252 perf_timer_reset_all()
253
254 # use a custom dependency resolver that just accumulates the dependencies
255 # (we'll pass these to Shiny in a moment)
256 dependencies <- list()
257 shiny_dependency_resolver <- function(deps) {
258 dependencies <<- deps
259 list()
260 }
261
262 # ensure that the document is not rendered to one page
263 output_opts <- list(
264 self_contained = FALSE,
265 copy_resources = TRUE,
266 dependency_resolver = shiny_dependency_resolver)
267
268 # remove console clutter from any previous renders
269 message("\f")
270
271 # merge our inputs with those supplied by the user and invoke render
272 args <- merge_lists(list(input = reactive_file(),
273 output_file = output_dest,
274 output_dir = dirname(output_dest),
275 output_options = output_opts,
276 intermediates_dir = dirname(output_dest),
277 runtime = "shiny"),
278 render_args)
279 result_path <- shiny::maskReactiveContext(do.call(render, args))
280
281 # ensure the resource folder exists, and map requests to it in Shiny
282 if (!dir_exists(resource_folder))
283 dir.create(resource_folder, recursive = TRUE)
284 shiny::addResourcePath(basename(resource_folder), resource_folder)
285
286 # extra dependency: emit performance information collected during render
287 dependencies <- append(dependencies, list(create_performance_dependency(resource_folder)))
288
289 # save the structured dependency information
290 write_shiny_deps(resource_folder, dependencies)
291
292 # attach rstudio rsiframe script if we are in rstudio (we do this after
293 # persisting the dependencies since this dependency is ephemeral)
294 if (nzchar(Sys.getenv("RSTUDIO")))
295 dependencies <- append(dependencies, list(html_dependency_rsiframe()))
296
297 # when the session ends, remove the rendered document and any supporting
298 # files, if they're not cacheable
299 if (!isTRUE(out$cacheable)) {
300 shiny::onReactiveDomainEnded(shiny::getDefaultReactiveDomain(), function() {
301 unlink(result_path)
302 unlink(resource_folder, recursive = TRUE)
303 })
304 }
305 shinyHTML_with_deps(result_path, dependencies)
306 })
307
308 doc_ui <- shiny::renderUI({
309 doc()
310 })
311
312 # For test snapshots. (The snapshotPreprocessOutput function was added
313 # in shiny 1.0.4.)
314 if (exists("snapshotPreprocessOutput", asNamespace("shiny"))) {
315 doc_ui <- shiny::snapshotPreprocessOutput(
316 doc_ui,
317 function(value) {
318 # Since the html data can be very large, just record a hash of it.
319 value$html <- sprintf("[html data sha1: %s]",
320 digest::digest(value$html, algo = "sha1", serialize = FALSE)
321 )
322
323 value
324 }
325 )
326 }
327
328 output$`__reactivedoc__` <- doc_ui
329 }
330 }
331
332 # create the Shiny UI function
333 rmarkdown_shiny_ui <- function(dir, file) {
334 function(req) {
335 # map requests to / to requests for the default--index.Rmd, or another if
336 # specified
337 req_path <- utils::URLdecode(req$PATH_INFO)
338 if (identical(req_path, "/")) {
339 req_path <- file
340 }
341
342 # request must be for an R Markdown or HTML document
343 ext <- tolower(xfun::file_ext(req_path))
344 if (!(ext %in% c("rmd", "qmd", "htm", "html"))) return(NULL)
345
346 # document must exist
347 target_file <- resolve_relative(dir, req_path)
348 if (is.null(target_file) || !file.exists(target_file)) {
349 return(NULL)
350 }
351
352 tags$div(
353 tags$head(
354 tags$script(src = "rmd_resources/rmd_loader.js"),
355 tags$link(href = "rmd_resources/rmd_loader.css", rel = "stylesheet")
356 ),
357
358 # Shiny shows the outer conditionalPanel as long as the document hasn't
359 # loaded; the inner rmd_loader is shown by rmd_loader.js as soon as
360 # we've been waiting a certain number of ms
361 shiny::conditionalPanel(
362 "!output.__reactivedoc__",
363 tags$div(
364 id = "rmd_loader_wrapper",
365 tags$div(id = "rmd_loader", style = "display: none",
366 tags$p("Please wait..."),
367 tags$img(src = "rmd_resources/rmd_loader.gif")))),
368 shiny::uiOutput("__reactivedoc__")
369 )
370 }
371 }
372
373 shinyHTML_with_deps <- function(html_file, deps) {
374
375 # read the html_file
376 html <- read_utf8(html_file)
377
378 # if we are running in RStudio and have local MathJax then serve locally
379 # (for static Rmds we do this substitution inside RStudio as we serve the
380 # html over our port, however these documents are served by Shiny so there
381 # is no opportunity to do the substituion)
382 if (nzchar(Sys.getenv("RSTUDIO"))) {
383 local_mathjax <- Sys.getenv("RMARKDOWN_MATHJAX_PATH")
384 if (nzchar(local_mathjax)) {
385 html <- gsub(pattern = "https://mathjax.rstudio.com/latest/MathJax.js?",
386 replacement = "mathjax-local/MathJax.js?",
387 x = html,
388 fixed = TRUE,
389 useBytes = TRUE)
390 shiny::addResourcePath("mathjax-local", local_mathjax)
391 }
392 }
393
394 # attach dependencies and return HTML
395 htmltools::attachDependencies(HTML(one_string(html)), deps)
396 }
397
398 #given an input file, return a list with values indicating whether the input
399 #file's Shiny document can be cached and, if so, its cached representation if
400 #available ' @import utils
401 rmd_cached_output <- function(input) {
402 # init return values
403 cacheable <- FALSE
404 cached <- FALSE
405 shiny_html <- NULL
406 resource_folder <- ""
407
408 # if the file is raw HTML, return it directly
409 if (tolower(xfun::file_ext(input)) %in% c("htm", "html")) {
410 return(list(
411 cacheable = TRUE,
412 cached = TRUE,
413 dest = "",
414 shiny_html = shinyHTML_with_deps(input, NULL),
415 resource_folder = ""))
416 }
417
418 # check to see if the file is a Shiny document
419 front_matter <- yaml_front_matter(input)
420 if (!is_shiny_classic(front_matter$runtime)) {
421
422 # If it's not a Shiny document, then its output is cacheable. Hash the file
423 # with its modified date to get a cache key.
424 cacheable <- TRUE
425 output_key <- digest::digest(paste(input, file.info(input)[4]),
426 algo = "md5", serialize = FALSE)
427
428 basetmp <- tempdir()
429
430 # On some machines, the TMP directory is /tmp and shared by all users.
431 # Caching data under /tmp/rmarkdown would mean that multiple users
432 # would try to access that same folder, which probably has permissions
433 # 700 by default. So namespace by username.
434 username <- Sys.info()[c("effective_user", "user", "login")]
435 username <- ifelse(username != "unknown", username, NA_character_)
436 username <- na.omit(username)
437 username <- head(username, 1)
438 if (length(username) == 1) {
439 if (!grepl("^[a-z0-9\\-\\_]+$", username, perl = TRUE, ignore.case = TRUE)) {
440 # If the user has anything remotely suspicious in their username, use a
441 # digest of the username instead, to prevent any possibility of jumping
442 # outside of the temp directory.
443 username <- substr(digest::digest(username, "md5"), 1, 12)
444 }
445 basetmp <- file.path(dirname(tempdir()), username)
446 }
447
448 output_dest <- paste(file.path(basetmp, "rmarkdown", output_key,
449 paste("rmd", output_key, sep = "_")),
450 "html", sep = ".")
451
452 # If the output is cacheable, it may also be already cached
453 if (file.exists(output_dest)) {
454 resource_folder <- knitr_files_dir(output_dest)
455 dependencies <- read_shiny_deps(resource_folder)
456 shiny_html <- shinyHTML_with_deps(output_dest, dependencies)
457 cached <- TRUE
458 }
459 } else {
460 # It's not cacheable, and should be rendered to a session-specific temporary
461 # directory, but with a predictable file name.
462 tmp_dir <- tempfile()
463 output_dest_name <- xfun::with_ext(basename(input), ".html")
464 output_dest <- file.path(tmp_dir, output_dest_name)
465 }
466 list(
467 cacheable = cacheable,
468 cached = cached,
469 dest = output_dest,
470 shiny_html = shiny_html,
471 resource_folder = resource_folder)
472 }
473
474 # resolve a path relative to a directory (from Shiny)
475 resolve_relative <- function(dir, relpath) {
476 abs.path <- file.path(dir, relpath)
477 if (!file.exists(abs.path))
478 return(NULL)
479 abs.path <- normalize_path(abs.path, must_work = TRUE)
480 dir <- normalize_path(dir, must_work = TRUE)
481 # trim the possible trailing slash under Windows
482 if (.Platform$OS.type == 'windows') dir <- sub('/$', '', dir)
483 if (nchar(abs.path) <= nchar(dir) + 1)
484 return(NULL)
485 if (substr(abs.path, 1, nchar(dir)) != dir ||
486 substr(abs.path, nchar(dir) + 1, nchar(dir) + 1) != '/') {
487 return(NULL)
488 }
489 return(abs.path)
490 }
491
492 # find 'name' in 'dir', without matching on case (from Shiny)
493 file.path.ci <- function(dir, name) {
494 default <- file.path(dir, name)
495 if (file.exists(default))
496 return(default)
497 if (!dir_exists(dir))
498 return(default)
499
500 matches <- list.files(dir, name, ignore.case = TRUE, full.names = TRUE,
501 include.dirs = TRUE)
502 # name is used as a pattern above and can match other files
503 # so we need to filter as if it was literal string
504 matches <- matches[tolower(name) == tolower(basename(matches))]
505 if (length(matches) == 0) return(default)
506 return(matches[[1]])
507 }
508
509 #' Delay Rendering for an Expression
510 #'
511 #' In a Shiny document, evaluate the given expression after the document has
512 #' finished rendering, instead of during render.
513 #'
514 #' This function is useful inside Shiny documents. It delays the
515 #' evaluation of its argument until the document has finished its initial
516 #' render, so that the document can be viewed before the calculation is
517 #' finished.
518 #'
519 #' Any expression that returns HTML can be wrapped in \code{render_delayed}.
520 #' @param expr The expression to evaluate.
521 #' @return An object representing the expression.
522 #' @note \code{expr} is evaluated in a \strong{copy} of the environment in which
523 #' the \code{render_delayed} call appears. Consequently, no side effects
524 #' created by \code{expr} are visible in succeeding expressions, nor are
525 #' changes to the environment after the call to \code{render_delayed} visible
526 #' to \code{expr}.
527 #'
528 #' \code{expr} must be an expression that produces HTML.
529 #' @examples
530 #' \dontrun{
531 #' # Add the following code to an R Markdown document
532 #'
533 #' div(Sys.time())
534 #'
535 #' render_delayed({
536 #' Sys.sleep(3) # simulate an expensive computation
537 #' div(Sys.time())
538 #' })
539 #'
540 #' div(Sys.time())
541 #' }
542 #' @export
543 render_delayed <- function(expr) {
544
545 # take a snapshot of the environment in which the expr should be rendered
546 env <- parent.frame()
547 env_snapshot <- new.env(parent = parent.env(env))
548 for (var in ls(env, all.names = TRUE))
549 assign(var, get(var, env), env_snapshot)
550
551 # take a snapshot of the current knitr and chunk options and the
552 # expression to be evaluated
553 assign("knitr_cached_chunk_opts", knitr::opts_current$get(), env_snapshot)
554 assign("knitr_cached_knit_opts", knitr::opts_knit$get(), env_snapshot)
555 assign("knitr_orig_expr", substitute(expr), env_snapshot)
556
557 # evaluate the expression at runtime
558 shiny::renderUI(quote({
559 knitr::opts_current$restore(knitr_cached_chunk_opts)
560 knitr::opts_knit$restore(knitr_cached_knit_opts)
561 HTML(knitr::knit_print(eval(knitr_orig_expr), knitr::opts_current$get()))
562 }),
563 env = env_snapshot,
564 quoted = TRUE)
565 }
566
567 is_shiny <- function(runtime, server = NULL) {
568 (!is.null(runtime) && grepl('^shiny', runtime)) ||
569 is_shiny_prerendered(runtime, server)
570 }
571
572 is_shiny_classic <- function(runtime) {
573 identical(runtime, "shiny")
574 }
575
576 is_shiny_prerendered <- function(runtime, server = NULL) {
577 if (identical(runtime, "shinyrmd") || identical(runtime, "shiny_prerendered")) {
578 TRUE
579 } else if (identical(server, "shiny")) {
580 TRUE
581 } else if (is.list(server) && identical(server[["type"]], "shiny")) {
582 TRUE
583 } else {
584 FALSE
585 }
586 }
587
588 write_shiny_deps <- function(files_dir,
589 deps) {
590 if (!dir_exists(files_dir)) dir.create(files_dir, recursive = TRUE)
591 deps_file <- file.path(files_dir, "dependencies.json")
592 deps_json <- jsonlite::serializeJSON(deps, pretty = TRUE)
593 write_utf8(deps_json, deps_file)
594 }
595
596 read_shiny_deps <- function(files_dir) {
597 deps_path <- file.path(files_dir, "dependencies.json")
598 if (file.exists(deps_path)) {
599 deps_json <- read_utf8(deps_path)
600 dependencies <- jsonlite::unserializeJSON(deps_json)
601
602 # attach rstudio rsiframe script if we are in rstudio
603 if (nzchar(Sys.getenv("RSTUDIO")))
604 dependencies <- append(dependencies, list(html_dependency_rsiframe()))
605
606 # return
607 dependencies
608 } else {
609 list()
610 }
611 }
612
613
614 # shiny:::setCurrentTheme() was added in 1.6 (we may export in next version)
615 set_current_theme <- function(theme) {
616 set_theme <- asNamespace("shiny")$setCurrentTheme
617 if (is.function(set_theme)) set_theme(theme)
618 }