Debian Codegraph @

R/shinywrappers.R

raw
1 utils::globalVariables('func', add = TRUE)
2
3 #' Mark a function as a render function
4 #'
5 #' `r lifecycle::badge("superseded")` Please use [`createRenderFunction()`] to
6 #' support async execution. (Shiny 1.1.0)
7 #'
8 #' Should be called by implementers of `renderXXX` functions in order to mark
9 #' their return values as Shiny render functions, and to provide a hint to Shiny
10 #' regarding what UI function is most commonly used with this type of render
11 #' function. This can be used in R Markdown documents to create complete output
12 #' widgets out of just the render function.
13 #'
14 #' Note that it is generally preferable to use [createRenderFunction()] instead
15 #' of `markRenderFunction()`. It essentially wraps up the user-provided
16 #' expression in the `transform` function passed to it, then passes the resulting
17 #' function to `markRenderFunction()`. It also provides a simpler calling
18 #' interface. There may be cases where `markRenderFunction()` must be used instead of
19 #' [createRenderFunction()] -- for example, when the `transform` parameter of
20 #' [createRenderFunction()] is not flexible enough for your needs.
21 #'
22 #' @param uiFunc A function that renders Shiny UI. Must take a single argument:
23 #' an output ID.
24 #' @param renderFunc A function that is suitable for assigning to a Shiny output
25 #' slot.
26 #' @param outputArgs A list of arguments to pass to the `uiFunc`. Render
27 #' functions should include `outputArgs = list()` in their own parameter list,
28 #' and pass through the value to `markRenderFunction`, to allow app authors to
29 #' customize outputs. (Currently, this is only supported for dynamically
30 #' generated UIs, such as those created by Shiny code snippets embedded in R
31 #' Markdown documents).
32 #' @param cacheHint One of `"auto"`, `FALSE`, or some other information to
33 #' identify this instance for caching using [bindCache()]. If `"auto"`, it
34 #' will try to automatically infer caching information. If `FALSE`, do not
35 #' allow caching for the object. Some render functions (such as [renderPlot])
36 #' contain internal state that makes them unsuitable for caching.
37 #' @param cacheWriteHook Used if the render function is passed to `bindCache()`.
38 #' This is an optional callback function to invoke before saving the value
39 #' from the render function to the cache. This function must accept one
40 #' argument, the value returned from `renderFunc`, and should return the value
41 #' to store in the cache.
42 #' @param cacheReadHook Used if the render function is passed to `bindCache()`.
43 #' This is an optional callback function to invoke after reading a value from
44 #' the cache (if there is a cache hit). The function will be passed one
45 #' argument, the value retrieved from the cache. This can be useful when some
46 #' side effect needs to occur for a render function to behave correctly. For
47 #' example, some render functions call [createWebDependency()] so that Shiny
48 #' is able to serve JS and CSS resources.
49 #' @return The `renderFunc` function, with annotations.
50 #'
51 #' @seealso [createRenderFunction()]
52 #' @export
53 markRenderFunction <- function(
54 uiFunc,
55 renderFunc,
56 outputArgs = list(),
57 cacheHint = "auto",
58 cacheWriteHook = NULL,
59 cacheReadHook = NULL
60 ) {
61 # (Do not emit warning for superseded code, "since there’s no risk if you keep using it")
62 # # This method is called by the superseding function, createRenderFunction().
63 # if (in_devmode()) {
64 # shinyDeprecated("1.1.0", "markRenderFunction()", "createRenderFunction()")
65 # }
66
67 force(renderFunc)
68
69 # a mutable object that keeps track of whether `useRenderFunction` has been
70 # executed (this usually only happens when rendering Shiny code snippets in
71 # an interactive R Markdown document); its initial value is FALSE
72 hasExecuted <- Mutable$new()
73 hasExecuted$set(FALSE)
74
75 if (is.null(uiFunc)) {
76 uiFunc <- function(id) {
77 pre(
78 "No UI/output function provided for render function. ",
79 "Please see ?shiny::markRenderFunction and ?shiny::createRenderFunction."
80 )
81 }
82 }
83
84 if (identical(cacheHint, "auto")) {
85 origUserFunc <- attr(renderFunc, "wrappedFunc", exact = TRUE)
86 # The result could be NULL, but don't warn now because it'll only affect
87 # users if they try to use caching. We'll warn when someone calls
88 # bindCache() on this object.
89 if (is.null(origUserFunc)) {
90 cacheHint <- NULL
91 } else {
92 # Add in the wrapper render function and they output function, because
93 # they can be useful for distinguishing two renderX functions that receive
94 # the same user expression but do different things with them (like
95 # renderText and renderPrint).
96 cacheHint <- list(
97 origUserFunc = origUserFunc,
98 renderFunc = renderFunc,
99 outputFunc = uiFunc
100 )
101 }
102 }
103
104 if (!is.null(cacheHint) && !is_false(cacheHint)) {
105 if (!is.list(cacheHint)) {
106 cacheHint <- list(cacheHint)
107 }
108 # For functions, remove the env and source refs because they can cause
109 # spurious differences.
110 # For expressions, remove source refs.
111 # For everything else, do nothing.
112 cacheHint <- lapply(cacheHint, function(x) {
113 if (is.function(x)) formalsAndBody(x)
114 else if (is_quosure(x)) zap_srcref(quo_get_expr(x))
115 else if (is.language(x)) zap_srcref(x)
116 else x
117 })
118 }
119
120 wrappedRenderFunc <- function(...) {
121 # if the user provided something through `outputArgs` BUT the
122 # `useRenderFunction` was not executed, then outputArgs will be ignored,
123 # so throw a warning to let user know the correct usage
124 if (length(outputArgs) != 0 && !hasExecuted$get()) {
125 warning("Unused argument: outputArgs. The argument outputArgs is only ",
126 "meant to be used when embedding snippets of Shiny code in an ",
127 "R Markdown code chunk (using runtime: shiny). When running a ",
128 "full Shiny app, please set the output arguments directly in ",
129 "the corresponding output function of your UI code.")
130 # stop warning from happening again for the same object
131 hasExecuted$set(TRUE)
132 }
133 ..stacktraceoff..(
134 if (is.null(formals(renderFunc))) renderFunc()
135 else renderFunc(...)
136 )
137 }
138
139 otelAttrs <-
140 otel_srcref_attributes(
141 attr(renderFunc, "wrappedFunc", exact = TRUE),
142 # Can't retrieve the render function used at this point, so just use NULL
143 fn_name = NULL
144 )
145
146 ret <- structure(
147 wrappedRenderFunc,
148 class = c("shiny.render.function", "function"),
149 outputFunc = uiFunc,
150 outputArgs = outputArgs,
151 hasExecuted = hasExecuted,
152 cacheHint = cacheHint,
153 cacheWriteHook = cacheWriteHook,
154 cacheReadHook = cacheReadHook,
155 otelAttrs = otelAttrs
156 )
157
158 if (has_otel_collect("reactivity")) {
159 ret <- enable_otel_shiny_render_function(ret)
160 }
161
162 ret
163 }
164
165 #' @export
166 print.shiny.render.function <- function(x, ...) {
167 cat_line("<shiny.render.function>")
168 }
169
170 #' Implement custom render functions
171 #'
172 #' Developer-facing utilities for implementing a custom `renderXXX()` function.
173 #' Before using these utilities directly, consider using the [`htmlwidgets`
174 #' package](http://www.htmlwidgets.org/develop_intro.html) to implement custom
175 #' outputs (i.e., custom `renderXXX()`/`xxxOutput()` functions). That said,
176 #' these utilities can be used more directly if a full-blown htmlwidget isn't
177 #' needed and/or the user-supplied reactive expression needs to be wrapped in
178 #' additional call(s).
179 #'
180 #' To implement a custom `renderXXX()` function, essentially 2 things are needed:
181 #' 1. Capture the user's reactive expression as a function.
182 #' * New `renderXXX()` functions can use `quoToFunction()` for this, but
183 #' already existing `renderXXX()` functions that contain `env` and `quoted`
184 #' parameters may want to continue using `installExprFunction()` for better
185 #' legacy support (see examples).
186 #' 2. Flag the resulting function (from 1) as a Shiny rendering function and
187 #' also provide a UI container for displaying the result of the rendering
188 #' function.
189 #' * `createRenderFunction()` is currently recommended (instead of
190 #' [markRenderFunction()]) for this step (see examples).
191 #'
192 #' @param func A function without parameters, that returns user data. If the
193 #' returned value is a promise, then the render function will proceed in async
194 #' mode.
195 #' @param transform A function that takes four arguments: `value`,
196 #' `session`, `name`, and `...` (for future-proofing). This
197 #' function will be invoked each time a value is returned from `func`,
198 #' and is responsible for changing the value into a JSON-ready value to be
199 #' JSON-encoded and sent to the browser.
200 #' @param outputFunc The UI function that is used (or most commonly used) with
201 #' this render function. This can be used in R Markdown documents to create
202 #' complete output widgets out of just the render function.
203 #' @inheritParams markRenderFunction
204 #' @return An annotated render function, ready to be assigned to an
205 #' `output` slot.
206 #'
207 #' @examples
208 #' # A custom render function that repeats the supplied value 3 times
209 #' renderTriple <- function(expr) {
210 #' # Wrap user-supplied reactive expression into a function
211 #' func <- quoToFunction(rlang::enquo0(expr))
212 #'
213 #' createRenderFunction(
214 #' func,
215 #' transform = function(value, session, name, ...) {
216 #' paste(rep(value, 3), collapse=", ")
217 #' },
218 #' outputFunc = textOutput
219 #' )
220 #' }
221 #'
222 #' # For better legacy support, consider using installExprFunction() over quoToFunction()
223 #' renderTripleLegacy <- function(expr, env = parent.frame(), quoted = FALSE) {
224 #' func <- installExprFunction(expr, "func", env, quoted)
225 #'
226 #' createRenderFunction(
227 #' func,
228 #' transform = function(value, session, name, ...) {
229 #' paste(rep(value, 3), collapse=", ")
230 #' },
231 #' outputFunc = textOutput
232 #' )
233 #' }
234 #'
235 #' # Test render function from the console
236 #' reactiveConsole(TRUE)
237 #'
238 #' v <- reactiveVal("basic")
239 #' r <- renderTriple({ v() })
240 #' r()
241 #' #> [1] "basic, basic, basic"
242 #'
243 #' # User can supply quoted code via rlang::quo(). Note that evaluation of the
244 #' # expression happens when r2() is invoked, not when r2 is created.
245 #' q <- rlang::quo({ v() })
246 #' r2 <- rlang::inject(renderTriple(!!q))
247 #' v("rlang")
248 #' r2()
249 #' #> [1] "rlang, rlang, rlang"
250 #'
251 #' # Supplying quoted code without rlang::quo() requires installExprFunction()
252 #' expr <- quote({ v() })
253 #' r3 <- renderTripleLegacy(expr, quoted = TRUE)
254 #' v("legacy")
255 #' r3()
256 #' #> [1] "legacy, legacy, legacy"
257 #'
258 #' # The legacy approach also supports with quosures (env is ignored in this case)
259 #' q <- rlang::quo({ v() })
260 #' r4 <- renderTripleLegacy(q, quoted = TRUE)
261 #' v("legacy-rlang")
262 #' r4()
263 #' #> [1] "legacy-rlang, legacy-rlang, legacy-rlang"
264 #'
265 #' # Turn off reactivity in the console
266 #' reactiveConsole(FALSE)
267 #'
268 #' @export
269 createRenderFunction <- function(
270 func,
271 transform = function(value, session, name, ...) value,
272 outputFunc = NULL,
273 outputArgs = NULL,
274 cacheHint = "auto",
275 cacheWriteHook = NULL,
276 cacheReadHook = NULL
277 ) {
278 renderFunc <- function(shinysession, name, ...) {
279 hybrid_chain(
280 ..stacktraceon..(func()),
281 function(value) {
282 transform(value, shinysession, name, ...)
283 }
284 )
285 }
286
287 # Hoist func's wrappedFunc attribute into renderFunc, so that when we pass
288 # renderFunc on to markRenderFunction, it is able to find the original user
289 # function.
290 attr(renderFunc, "wrappedFunc") <- attr(func, "wrappedFunc", exact = TRUE)
291
292 markRenderFunction(outputFunc, renderFunc, outputArgs, cacheHint,
293 cacheWriteHook, cacheReadHook)
294 }
295
296 useRenderFunction <- function(renderFunc, inline = FALSE) {
297 outputFunction <- attr(renderFunc, "outputFunc")
298 outputArgs <- attr(renderFunc, "outputArgs")
299 hasExecuted <- attr(renderFunc, "hasExecuted")
300 hasExecuted$set(TRUE)
301
302 for (arg in names(outputArgs)) {
303 if (!arg %in% names(formals(outputFunction))) {
304 stop(paste0("Unused argument: in 'outputArgs', '",
305 arg, "' is not an valid argument for ",
306 "the output function"))
307 outputArgs[[arg]] <- NULL
308 }
309 }
310
311 id <- createUniqueId(8, "out")
312
313 o <- getDefaultReactiveDomain()$output
314 if (!is.null(o)) {
315 o[[id]] <- renderFunc
316 # If there's a namespace, we must respect it
317 id <- getDefaultReactiveDomain()$ns(id)
318 }
319
320 # Make the id the first positional argument
321 outputArgs <- c(list(id), outputArgs)
322
323 if (is.logical(formals(outputFunction)[["inline"]]) && !("inline" %in% names(outputArgs))) {
324 outputArgs[["inline"]] <- inline
325 }
326
327 do.call(outputFunction, outputArgs)
328 }
329
330 #' @export
331 #' @method as.tags shiny.render.function
332 as.tags.shiny.render.function <- function(x, ..., inline = FALSE) {
333 useRenderFunction(x, inline = inline)
334 }
335
336 # Get relevant attributes from a render function object.
337 renderFunctionAttributes <- function(x) {
338 attrs <- c("outputFunc", "outputArgs", "hasExecuted", "cacheHint", "otelAttrs")
339 names(attrs) <- attrs
340 lapply(attrs, function(name) attr(x, name, exact = TRUE))
341 }
342
343 # Add a named list of attributes to an object
344 addAttributes <- function(x, attrs) {
345 nms <- names(attrs)
346 for (i in seq_along(attrs)) {
347 attr(x, nms[i]) <- attrs[[i]]
348 }
349 x
350 }
351
352
353 #' Mark a render function with attributes that will be used by the output
354 #'
355 #' @inheritParams markRenderFunction
356 #' @param snapshotExclude If TRUE, exclude the output from test snapshots.
357 #' @param snapshotPreprocess A function for preprocessing the value before
358 #' taking a test snapshot.
359 #'
360 #' @keywords internal
361 markOutputAttrs <- function(renderFunc, snapshotExclude = NULL,
362 snapshotPreprocess = NULL)
363 {
364 # Add the outputAttrs attribute if necessary
365 if (is.null(attr(renderFunc, "outputAttrs", TRUE))) {
366 attr(renderFunc, "outputAttrs") <- list()
367 }
368
369 if (!is.null(snapshotExclude)) {
370 attr(renderFunc, "outputAttrs")$snapshotExclude <- snapshotExclude
371 }
372
373 if (!is.null(snapshotPreprocess)) {
374 attr(renderFunc, "outputAttrs")$snapshotPreprocess <- snapshotPreprocess
375 }
376
377 renderFunc
378 }
379
380 #' Image file output
381 #'
382 #' Renders a reactive image that is suitable for assigning to an `output`
383 #' slot.
384 #'
385 #' The expression `expr` must return a list containing the attributes for
386 #' the `img` object on the client web page. For the image to display,
387 #' properly, the list must have at least one entry, `src`, which is the
388 #' path to the image file. It may also useful to have a `contentType`
389 #' entry specifying the MIME type of the image. If one is not provided,
390 #' `renderImage` will try to autodetect the type, based on the file
391 #' extension.
392 #'
393 #' Other elements such as `width`, `height`, `class`, and
394 #' `alt`, can also be added to the list, and they will be used as
395 #' attributes in the `img` object.
396 #'
397 #' The corresponding HTML output tag should be `div` or `img` and have
398 #' the CSS class name `shiny-image-output`.
399 #'
400 #' @seealso
401 #' * For more details on how the images are generated, and how to control
402 #' the output, see [plotPNG()].
403 #' * Use [outputOptions()] to set general output options for an image output.
404 #'
405 #' @param expr An expression that returns a list.
406 #' @inheritParams renderUI
407 #' @param deleteFile Should the file in `func()$src` be deleted after
408 #' it is sent to the client browser? Generally speaking, if the image is a
409 #' temp file generated within `func`, then this should be `TRUE`;
410 #' if the image is not a temp file, this should be `FALSE`. (For backward
411 #' compatibility reasons, if this argument is missing, a warning will be
412 #' emitted, and if the file is in the temp directory it will be deleted. In
413 #' the future, this warning will become an error.)
414 #' @param outputArgs A list of arguments to be passed through to the implicit
415 #' call to [imageOutput()] when `renderImage` is used in an
416 #' interactive R Markdown document.
417 #' @export
418 #'
419 #' @examples
420 #' ## Only run examples in interactive R sessions
421 #' if (interactive()) {
422 #' options(device.ask.default = FALSE)
423 #'
424 #' ui <- fluidPage(
425 #' sliderInput("n", "Number of observations", 2, 1000, 500),
426 #' plotOutput("plot1"),
427 #' plotOutput("plot2"),
428 #' plotOutput("plot3")
429 #' )
430 #'
431 #' server <- function(input, output, session) {
432 #'
433 #' # A plot of fixed size
434 #' output$plot1 <- renderImage({
435 #' # A temp file to save the output. It will be deleted after renderImage
436 #' # sends it, because deleteFile=TRUE.
437 #' outfile <- tempfile(fileext='.png')
438 #'
439 #' # Generate a png
440 #' png(outfile, width=400, height=400)
441 #' hist(rnorm(input$n))
442 #' dev.off()
443 #'
444 #' # Return a list
445 #' list(src = outfile,
446 #' alt = "This is alternate text")
447 #' }, deleteFile = TRUE)
448 #'
449 #' # A dynamically-sized plot
450 #' output$plot2 <- renderImage({
451 #' # Read plot2's width and height. These are reactive values, so this
452 #' # expression will re-run whenever these values change.
453 #' width <- session$clientData$output_plot2_width
454 #' height <- session$clientData$output_plot2_height
455 #'
456 #' # A temp file to save the output.
457 #' outfile <- tempfile(fileext='.png')
458 #'
459 #' png(outfile, width=width, height=height)
460 #' hist(rnorm(input$n))
461 #' dev.off()
462 #'
463 #' # Return a list containing the filename
464 #' list(src = outfile,
465 #' width = width,
466 #' height = height,
467 #' alt = "This is alternate text")
468 #' }, deleteFile = TRUE)
469 #'
470 #' # Send a pre-rendered image, and don't delete the image after sending it
471 #' # NOTE: For this example to work, it would require files in a subdirectory
472 #' # named images/
473 #' output$plot3 <- renderImage({
474 #' # When input$n is 1, filename is ./images/image1.jpeg
475 #' filename <- normalizePath(file.path('./images',
476 #' paste('image', input$n, '.jpeg', sep='')))
477 #'
478 #' # Return a list containing the filename
479 #' list(src = filename)
480 #' }, deleteFile = FALSE)
481 #' }
482 #'
483 #' shinyApp(ui, server)
484 #' }
485 renderImage <- function(expr, env = parent.frame(), quoted = FALSE,
486 deleteFile, outputArgs=list())
487 {
488 func <- installExprFunction(expr, "func", env, quoted, label = "renderImage")
489
490 # missing() must be used directly within the function with the given arg
491 if (missing(deleteFile)) {
492 deleteFile <- NULL
493 }
494
495 # Tracks whether we've reported the `deleteFile` warning yet; we don't want to
496 # do it on every invalidation (though we will end up doing it at least once
497 # per output per session).
498 warned <- FALSE
499
500 createRenderFunction(func,
501 transform = function(imageinfo, session, name, ...) {
502 shouldDelete <- deleteFile
503
504 # jcheng 2020-05-08
505 #
506 # Until Shiny 1.5.0, the default for deleteFile was, incredibly, TRUE.
507 # Changing it to default to FALSE might cause existing Shiny apps to pile
508 # up images in their temp directory (for long lived R processes). Not
509 # having a default (requiring explicit value) is the right long-term move,
510 # but would break today's apps.
511 #
512 # Compromise we decided on was to eventually require TRUE/FALSE, but for
513 # now, change the default behavior to only delete temp files; and emit a
514 # warning encouraging people to not rely on the default.
515 if (is.null(shouldDelete)) {
516 shouldDelete <- isTRUE(try(silent = TRUE,
517 file.exists(imageinfo$src) && isTemp(imageinfo$src, mustExist = TRUE)
518 ))
519
520 if (!warned) {
521 warned <<- TRUE
522 warning("The renderImage output named '",
523 getCurrentOutputInfo()$name,
524 "' is missing the deleteFile argument; as of Shiny 1.5.0, you must ",
525 "use deleteFile=TRUE or deleteFile=FALSE. (This warning will ",
526 "become an error in a future version of Shiny.)",
527 call. = FALSE
528 )
529 }
530 }
531
532 if (shouldDelete) {
533 on.exit(unlink(imageinfo$src), add = TRUE)
534 }
535
536 # If contentType not specified, autodetect based on extension
537 contentType <- imageinfo$contentType %||% getContentType(imageinfo$src)
538
539 # Extra values are everything in imageinfo except 'src' and 'contentType'
540 extra_attr <- imageinfo[!names(imageinfo) %in% c('src', 'contentType')]
541
542 # Return a list with src, and other img attributes
543 c(src = session$fileUrl(name, file=imageinfo$src, contentType=contentType),
544 extra_attr)
545 },
546 imageOutput,
547 outputArgs,
548 cacheHint = FALSE
549 )
550 }
551
552 # TODO: If we ever take a dependency on fs, it'd be great to replace this with
553 # fs::path_has_parent().
554 isTemp <- function(path, tempDir = tempdir(), mustExist) {
555 if (!isTRUE(mustExist)) {
556 # jcheng 2020-05-11: I added mustExist just to make it totally obvious that
557 # the path must exist. We don't support the case where the file doesn't
558 # exist because it makes normalizePath unusable, and it's a bit scary
559 # security-wise to compare paths without normalization. Using fs would fix
560 # this as it knows how to normalize paths that don't exist.
561 stop("isTemp(mustExist=FALSE) is not implemented")
562 }
563
564 if (mustExist && !file.exists(path)) {
565 stop("path does not exist")
566 }
567
568 if (nchar(tempDir) == 0 || !dir.exists(tempDir)) {
569 # This should never happen, but just to be super paranoid...
570 stop("invalid temp dir")
571 }
572
573 path <- normalizePath(path, winslash = "/", mustWork = mustExist)
574
575 tempDir <- normalizePath(tempDir, winslash = "/", mustWork = TRUE)
576 if (path == tempDir) {
577 return(FALSE)
578 }
579
580 tempDir <- ensure_trailing_slash(tempDir)
581 if (path == tempDir) {
582 return(FALSE)
583 }
584
585 return(substr(path, 1, nchar(tempDir)) == tempDir)
586 }
587
588 #' Text Output
589 #'
590 #' @description
591 #' `renderPrint()` prints the result of `expr`, while `renderText()` pastes it
592 #' together into a single string. `renderPrint()` is equivalent to [print()];
593 #' `renderText()` is equivalent to [cat()]. Both functions capture all other
594 #' printed output generated while evaluating `expr`.
595 #'
596 #' `renderPrint()` is usually paired with [verbatimTextOutput()];
597 #' `renderText()` is usually paired with [textOutput()].
598 #'
599 #' @details
600 #' The corresponding HTML output tag can be anything (though `pre` is
601 #' recommended if you need a monospace font and whitespace preserved) and should
602 #' have the CSS class name `shiny-text-output`.
603 #'
604 #' @return
605 #' For `renderPrint()`, note the given expression returns `NULL` then `NULL`
606 #' will actually be visible in the output. To display nothing, make your
607 #' function return [invisible()].
608 #'
609 #' @param expr An expression to evaluate.
610 #' @inheritParams renderUI
611 #' @param width Width of printed output.
612 #' @param outputArgs A list of arguments to be passed through to the implicit
613 #' call to [verbatimTextOutput()] or [textOutput()] when the functions are
614 #' used in an interactive RMarkdown document.
615 #'
616 #' @example res/text-example.R
617 #' @seealso [outputOptions()]
618 #' @export
619 renderPrint <- function(expr, env = parent.frame(), quoted = FALSE,
620 width = getOption('width'), outputArgs=list())
621 {
622 func <- installExprFunction(expr, "func", env, quoted, label = "renderPrint")
623
624 # Set a promise domain that sets the console width
625 # and captures output
626 # op <- options(width = width)
627 # on.exit(options(op), add = TRUE)
628
629 renderFunc <- function(shinysession, name, ...) {
630 domain <- createRenderPrintPromiseDomain(width)
631 hybrid_chain(
632 {
633 with_promise_domain(domain, ..stacktraceon..(func()))
634 },
635 function(value) {
636 res <- withVisible(value)
637 if (res$visible) {
638 cat(file = domain$conn, paste(utils::capture.output(res$value, append = TRUE), collapse = "\n"))
639 }
640 paste(readLines(domain$conn, warn = FALSE), collapse = "\n")
641 },
642 finally = function() {
643 close(domain$conn)
644 }
645 )
646 }
647
648 markRenderFunction(
649 verbatimTextOutput,
650 renderFunc,
651 outputArgs,
652 cacheHint = list(
653 label = "renderPrint",
654 origUserExpr = installedFuncExpr(func)
655 )
656 )
657 }
658
659 createRenderPrintPromiseDomain <- function(width) {
660 f <- file()
661
662 new_promise_domain(
663 wrapOnFulfilled = function(onFulfilled) {
664 force(onFulfilled)
665 function(...) {
666 op <- options(width = width)
667 on.exit(options(op), add = TRUE)
668
669 sink(f, append = TRUE)
670 on.exit(sink(NULL), add = TRUE)
671
672 onFulfilled(...)
673 }
674 },
675 wrapOnRejected = function(onRejected) {
676 force(onRejected)
677 function(...) {
678 op <- options(width = width)
679 on.exit(options(op), add = TRUE)
680
681 sink(f, append = TRUE)
682 on.exit(sink(NULL), add = TRUE)
683
684 onRejected(...)
685 }
686 },
687 wrapSync = function(expr) {
688 op <- options(width = width)
689 on.exit(options(op), add = TRUE)
690
691 sink(f, append = TRUE)
692 on.exit(sink(NULL), add = TRUE)
693
694 force(expr)
695 },
696 conn = f
697 )
698 }
699
700 #' @param sep A separator passed to `cat` to be appended after each
701 #' element.
702 #' @export
703 #' @rdname renderPrint
704 renderText <- function(expr, env = parent.frame(), quoted = FALSE,
705 outputArgs=list(), sep=" ") {
706
707 func <- installExprFunction(expr, "func", env, quoted, label = "renderText")
708
709 createRenderFunction(
710 func,
711 function(value, session, name, ...) {
712 paste(utils::capture.output(cat(value, sep=sep)), collapse="\n")
713 },
714 textOutput,
715 outputArgs
716 )
717 }
718
719 #' UI Output
720 #'
721 #' Renders reactive HTML using the Shiny UI library.
722 #'
723 #' The corresponding HTML output tag should be `div` and have the CSS class
724 #' name `shiny-html-output` (or use [uiOutput()]).
725 #'
726 #' @param expr An expression that returns a Shiny tag object, [HTML()],
727 #' or a list of such objects.
728 #' @template param-env
729 #' @templateVar x expr
730 #' @templateVar env env
731 #' @templateVar quoted quoted
732 #' @template param-quoted
733 #' @templateVar x expr
734 #' @templateVar quoted quoted
735 #' @param outputArgs A list of arguments to be passed through to the implicit
736 #' call to [uiOutput()] when `renderUI` is used in an
737 #' interactive R Markdown document.
738 #'
739 #' @seealso [uiOutput()], [outputOptions()]
740 #' @export
741 #' @examples
742 #' ## Only run examples in interactive R sessions
743 #' if (interactive()) {
744 #'
745 #' ui <- fluidPage(
746 #' uiOutput("moreControls")
747 #' )
748 #'
749 #' server <- function(input, output) {
750 #' output$moreControls <- renderUI({
751 #' tagList(
752 #' sliderInput("n", "N", 1, 1000, 500),
753 #' textInput("label", "Label")
754 #' )
755 #' })
756 #' }
757 #' shinyApp(ui, server)
758 #' }
759 #'
760 renderUI <- function(expr, env = parent.frame(), quoted = FALSE,
761 outputArgs = list())
762 {
763 func <- installExprFunction(expr, "func", env, quoted, label = "renderUI")
764
765 createRenderFunction(
766 func,
767 function(result, shinysession, name, ...) {
768 if (is.null(result) || length(result) == 0)
769 return(NULL)
770
771 processDeps(result, shinysession)
772 },
773 uiOutput,
774 outputArgs
775 )
776 }
777
778 #' File Downloads
779 #'
780 #' Allows content from the Shiny application to be made available to the user as
781 #' file downloads (for example, downloading the currently visible data as a CSV
782 #' file). Both filename and contents can be calculated dynamically at the time
783 #' the user initiates the download. Assign the return value to a slot on
784 #' `output` in your server function, and in the UI use
785 #' [downloadButton()] or [downloadLink()] to make the
786 #' download available.
787 #'
788 #' @param filename A string of the filename, including extension, that the
789 #' user's web browser should default to when downloading the file; or a
790 #' function that returns such a string. (Reactive values and functions may be
791 #' used from this function.)
792 #' @param content A function that takes a single argument `file` that is a
793 #' file path (string) of a nonexistent temp file, and writes the content to
794 #' that file path. (Reactive values and functions may be used from this
795 #' function.)
796 #' @param contentType A string of the download's
797 #' [content type](https://en.wikipedia.org/wiki/Internet_media_type), for
798 #' example `"text/csv"` or `"image/png"`. If `NULL`, the content type
799 #' will be guessed based on the filename extension, or
800 #' `application/octet-stream` if the extension is unknown.
801 #' @param outputArgs A list of arguments to be passed through to the implicit
802 #' call to [downloadButton()] when `downloadHandler` is used
803 #' in an interactive R Markdown document.
804 #'
805 #' @examples
806 #' ## Only run examples in interactive R sessions
807 #' if (interactive()) {
808 #'
809 #' ui <- fluidPage(
810 #' downloadButton("downloadData", "Download")
811 #' )
812 #'
813 #' server <- function(input, output) {
814 #' # Our dataset
815 #' data <- mtcars
816 #'
817 #' output$downloadData <- downloadHandler(
818 #' filename = function() {
819 #' paste("data-", Sys.Date(), ".csv", sep="")
820 #' },
821 #' content = function(file) {
822 #' write.csv(data, file)
823 #' }
824 #' )
825 #' }
826 #'
827 #' shinyApp(ui, server)
828 #' }
829 #'
830 #' @seealso
831 #' * The download handler, like other outputs, is suspended (disabled) by
832 #' default for download buttons and links that are hidden. Use
833 #' [outputOptions()] to control this behavior, e.g. to set
834 #' `suspendWhenHidden = FALSE` if the download is initiated by
835 #' programmatically clicking on the download button using JavaScript.
836 #' @export
837 downloadHandler <- function(filename, content, contentType=NULL, outputArgs=list()) {
838 renderFunc <- function(shinysession, name, ...) {
839 shinysession$registerDownload(name, filename, contentType, content)
840 }
841 snapshotExclude(
842 markRenderFunction(downloadButton, renderFunc, outputArgs, cacheHint = FALSE)
843 )
844 }
845
846 #' Table output with the JavaScript DataTables library
847 #'
848 #' @description
849 #' `r lifecycle::badge("deprecated")`
850 #'
851 #' This function is deprecated, use
852 #' [DT::renderDT()](https://rstudio.github.io/DT/shiny.html) instead. It
853 #' provides a superset of functionality, better performance, and better user
854 #' experience.
855 #'
856 #' @param expr An expression that returns a data frame or a matrix.
857 #' @inheritParams renderTable
858 #' @param options A list of initialization options to be passed to DataTables,
859 #' or a function to return such a list. You can find a complete list of
860 #' options at <https://datatables.net/reference/option/>.
861 #'
862 #' Any top-level strings with class `"AsIs"` (as created by [I()]) will be
863 #' evaluated in JavaScript. This is useful when the type of the option value
864 #' is not supported in JSON, e.g., a JavaScript function, which can be
865 #' obtained by evaluating a character string. This only applies to the
866 #' root-level elements of options list, and does not worked for lower-level
867 #' elements in the list.
868 #' @param searchDelay The delay for searching, in milliseconds (to avoid too
869 #' frequent search requests).
870 #' @param callback A JavaScript function to be applied to the DataTable object.
871 #' This is useful for DataTables plug-ins, which often require the DataTable
872 #' instance to be available.
873 #' @param escape Whether to escape HTML entities in the table: `TRUE` means
874 #' to escape the whole table, and `FALSE` means not to escape it.
875 #' Alternatively, you can specify numeric column indices or column names to
876 #' indicate which columns to escape, e.g. `1:5` (the first 5 columns),
877 #' `c(1, 3, 4)`, or `c(-1, -3)` (all columns except the first and
878 #' third), or `c('Species', 'Sepal.Length')`.
879 #' @param outputArgs A list of arguments to be passed through to the implicit
880 #' call to `dataTableOutput()` when `renderDataTable()` is used
881 #' in an interactive R Markdown document.
882 #' @export
883 #' @inheritParams renderPlot
884 #' @examples
885 #' ## Only run this example in interactive R sessions
886 #' if (interactive()) {
887 #' # pass a callback function to DataTables using I()
888 #' shinyApp(
889 #' ui = fluidPage(
890 #' fluidRow(
891 #' column(12,
892 #' dataTableOutput('table')
893 #' )
894 #' )
895 #' ),
896 #' server = function(input, output) {
897 #' output$table <- renderDataTable(iris,
898 #' options = list(
899 #' pageLength = 5,
900 #' initComplete = I("function(settings, json) {alert('Done.');}")
901 #' )
902 #' )
903 #' }
904 #' )
905 #' }
906 #' @keywords internal
907 renderDataTable <- function(expr, options = NULL, searchDelay = 500,
908 callback = 'function(oTable) {}', escape = TRUE,
909 env = parent.frame(), quoted = FALSE,
910 outputArgs = list()) {
911
912 legacy <- useLegacyDataTable(
913 from = "shiny::renderDataTable()",
914 to = "DT::renderDT()"
915 )
916
917 if (!quoted) {
918 expr <- substitute(expr)
919 quoted <- TRUE
920 }
921
922 if (legacy) {
923
924 legacyRenderDataTable(
925 expr, env = env, quoted = quoted,
926 options = options,
927 searchDelay = searchDelay,
928 callback = callback,
929 escape = escape,
930 outputArgs = outputArgs
931 )
932
933 } else {
934
935 if (!missing(searchDelay)) {
936 warning("Ignoring renderDataTable()'s searchDelay value (since DT::renderDT() has no equivalent).")
937 }
938
939 force(options)
940 force(callback)
941 force(escape)
942 force(outputArgs)
943
944 DT::renderDataTable(
945 expr, env = env, quoted = quoted,
946 options = if (is.null(options)) list() else options,
947 # Turn function into a statement
948 callback = DT::JS(paste0("(", callback, ")(table)")),
949 escape = escape,
950 outputArgs = outputArgs
951 )
952 }
953 }
954
955
956 legacyRenderDataTable <- function(expr, options = NULL, searchDelay = 500,
957 callback = 'function(oTable) {}', escape = TRUE,
958 env = parent.frame(), quoted = FALSE,
959 outputArgs=list()) {
960
961 func <- installExprFunction(expr, "func", env, quoted, label = "renderDataTable")
962
963 renderFunc <- function(shinysession, name, ...) {
964 if (is.function(options)) options <- options()
965 options <- checkDT9(options)
966 res <- checkAsIs(options)
967 hybrid_chain(
968 ..stacktraceon..(func()),
969 function(data) {
970 if (length(dim(data)) != 2) return() # expects a rectangular data object
971 if (is.data.frame(data)) data <- as.data.frame(data)
972 action <- shinysession$registerDataObj(name, data, dataTablesJSON)
973 colnames <- colnames(data)
974 # if escape is column names, turn names to numeric indices
975 if (is.character(escape)) {
976 escape <- stats::setNames(seq_len(ncol(data)), colnames)[escape]
977 if (any(is.na(escape)))
978 stop("Some column names in the 'escape' argument not found in data")
979 }
980 colnames[escape] <- htmlEscape(colnames[escape])
981 if (!is.logical(escape)) {
982 if (!is.numeric(escape))
983 stop("'escape' must be TRUE, FALSE, or a numeric vector, or column names")
984 escape <- paste(escape, collapse = ',')
985 }
986 list(
987 colnames = colnames, action = action, options = res$options,
988 evalOptions = if (length(res$eval)) I(res$eval), searchDelay = searchDelay,
989 callback = paste(callback, collapse = '\n'), escape = escape
990 )
991 }
992 )
993 }
994
995 renderFunc <- markRenderFunction(dataTableOutput, renderFunc, outputArgs,
996 cacheHint = FALSE)
997
998 renderFunc <- snapshotPreprocessOutput(renderFunc, function(value) {
999 # Remove the action field so that it's not saved in test snapshots. It
1000 # contains a value that changes every time an app is run, and shouldn't be
1001 # stored for test snapshots. It will be something like:
1002 # "session/e0d14d3fe97f672f9655a127f2a1e079/dataobj/table?w=&nonce=7f5d6d54e22450a3"
1003 value$action <- NULL
1004 value
1005 })
1006
1007 renderFunc
1008 }
1009
1010 # a data frame containing the DataTables 1.9 and 1.10 names
1011 DT10Names <- function() {
1012 rbind(
1013 utils::read.table(
1014 system_file('www/shared/datatables/upgrade1.10.txt', package = 'shiny'),
1015 stringsAsFactors = FALSE
1016 ),
1017 c('aoColumns', 'Removed') # looks like an omission on the upgrade guide
1018 )
1019 }
1020
1021 # check DataTables 1.9.x options, and give instructions for upgrading to 1.10.x
1022 checkDT9 <- function(options) {
1023 nms <- names(options)
1024 if (length(nms) == 0L) return(options)
1025 DT10 <- DT10Names()
1026 # e.g. the top level option name for oLanguage.sSearch should be oLanguage
1027 i <- nms %in% gsub('[.].*', '', DT10[, 1])
1028 if (!any(i)) return(options) # did not see old option names, ready to go!
1029 msg <- paste(
1030 'shiny (>= 0.10.2) has upgraded DataTables from 1.9.4 to 1.10.2, ',
1031 'and DataTables 1.10.x uses different parameter names with 1.9.x. ',
1032 'Please follow the upgrade guide https://datatables.net/upgrade/1.10-convert',
1033 ' to change your DataTables parameter names:\n\n',
1034 paste(utils::formatUL(nms[i]), collapse = '\n'), '\n', sep = ''
1035 )
1036 j <- gsub('[.].*', '', DT10[, 1]) %in% nms
1037 # I cannot help you upgrade automatically in these cases, so I have to stop
1038 if (any(grepl('[.]', DT10[j, 1])) || any(grepl('[.]', DT10[j, 2]))) stop(msg)
1039 warning(msg)
1040 nms10 <- DT10[match(nms[i], DT10[, 1]), 2]
1041 if (any(nms10 == 'Removed')) stop(
1042 "These parameters have been removed in DataTables 1.10.x:\n\n",
1043 paste(utils::formatUL(nms[i][nms10 == 'Removed']), collapse = '\n'),
1044 "\n\n", msg
1045 )
1046 names(options)[i] <- nms10
1047 options
1048 }