Debian Codegraph @

R/shiny-options.R

raw
1 .globals$options <- list()
2
3 #' @param name Name of an option to get.
4 #' @param default Value to be returned if the option is not currently set.
5 #' @rdname shinyOptions
6 #' @export
7 getShinyOption <- function(name, default = NULL) {
8 # Make sure to use named (not numeric) indexing
9 name <- as.character(name)
10
11 # Check if there's a current session
12 session <- getDefaultReactiveDomain()
13 if (!is.null(session)) {
14 if (name %in% names(session$options)) {
15 return(session$options[[name]])
16 } else {
17 return(default)
18 }
19 }
20
21 # Check if there's a current app
22 app_state <- getCurrentAppState()
23 if (!is.null(app_state)) {
24 if (name %in% names(app_state$options)) {
25 return(app_state$options[[name]])
26 } else {
27 return(default)
28 }
29 }
30
31 # If we got here, look in global options
32 if (name %in% names(.globals$options)) {
33 return(.globals$options[[name]])
34 } else {
35 return(default)
36 }
37 }
38
39 #' Get or set Shiny options
40 #'
41 #' @description
42 #'
43 #' There are two mechanisms for working with options for Shiny. One is the
44 #' [options()] function, which is part of base R, and the other is the
45 #' `shinyOptions()` function, which is in the Shiny package. The reason for
46 #' these two mechanisms is has to do with legacy code and scoping.
47 #'
48 #' The [options()] function sets options globally, for the duration of the R
49 #' process. The [getOption()] function retrieves the value of an option. All
50 #' shiny related options of this type are prefixed with `"shiny."`.
51 #'
52 #' The `shinyOptions()` function sets the value of a shiny option, but unlike
53 #' `options()`, it is not always global in scope; the options may be scoped
54 #' globally, to an application, or to a user session in an application,
55 #' depending on the context. The `getShinyOption()` function retrieves a value
56 #' of a shiny option. Currently, the options set via `shinyOptions` are for
57 #' internal use only.
58 #'
59 #' @section Options with `options()`:
60 #'
61 #' \describe{
62 #' \item{shiny.autoreload (defaults to `FALSE`)}{If `TRUE` when a Shiny app is launched, the
63 #' app directory will be continually monitored for changes to files that
64 #' have the extensions: r, htm, html, js, css, png, jpg, jpeg, gif. If any
65 #' changes are detected, all connected Shiny sessions are reloaded. This
66 #' allows for fast feedback loops when tweaking Shiny UI.
67 #'
68 #' Monitoring for changes is no longer expensive, thanks to the \pkg{watcher}
69 #' package, but this feature is still intended only for development.
70 #'
71 #' You can customize the file patterns Shiny will monitor by setting the
72 #' shiny.autoreload.pattern option. For example, to monitor only `ui.R`:
73 #' `options(shiny.autoreload.pattern = glob2rx("ui.R"))`.
74 #'
75 #' As mentioned above, Shiny no longer polls watched files for changes.
76 #' Instead, using \pkg{watcher}, Shiny is notified of file changes as they
77 #' occur. These changes are batched together within a customizable latency
78 #' period. You can adjust this period by setting
79 #' `options(shiny.autoreload.interval = 2000)` (in milliseconds). This value
80 #' converted to seconds and passed to the `latency` argument of
81 #' [watcher::watcher()]. The default latency is 250ms.}
82 #' \item{shiny.deprecation.messages (defaults to `TRUE`)}{This controls whether messages for
83 #' deprecated functions in Shiny will be printed. See
84 #' [shinyDeprecated()] for more information.}
85 #' \item{shiny.error (defaults to `NULL`)}{This can be a function which is called when an error
86 #' occurs. For example, `options(shiny.error=recover)` will result a
87 #' the debugger prompt when an error occurs.}
88 #' \item{shiny.fullstacktrace (defaults to `FALSE`)}{Controls whether "pretty" (`FALSE`) or full
89 #' stack traces (`TRUE`) are dumped to the console when errors occur during Shiny app execution.
90 #' Pretty stack traces attempt to only show user-supplied code, but this pruning can't always
91 #' be done 100% correctly.}
92 #' \item{shiny.host (defaults to `"127.0.0.1"`)}{The IP address that Shiny should listen on. See
93 #' [runApp()] for more information.}
94 #' \item{shiny.jquery.version (defaults to `3`)}{The major version of jQuery to use.
95 #' Currently only values of `3` or `1` are supported. If `1`, then jQuery 1.12.4 is used. If `3`,
96 #' then jQuery `r version_jquery` is used.}
97 #' \item{shiny.json.digits (defaults to `I(16)`)}{Max number of digits to use when converting
98 #' numbers to JSON format to send to the client web browser. Use [I()] to specify significant digits.
99 #' Use `NA` for max precision.}
100 #' \item{shiny.launch.browser (defaults to `interactive()`)}{A boolean which controls the default behavior
101 #' when an app is run. See [runApp()] for more information.}
102 #' \item{shiny.mathjax.url (defaults to `"https://mathjax.rstudio.com/latest/MathJax.js"`)}{
103 #' The URL that should be used to load MathJax, via [withMathJax()].}
104 #' \item{shiny.mathjax.config (defaults to `"config=TeX-AMS-MML_HTMLorMML"`)}{The querystring
105 #' used to load MathJax, via [withMathJax()].}
106 #' \item{shiny.maxRequestSize (defaults to 5MB)}{This is a number which specifies the maximum
107 #' web request size, which serves as a size limit for file uploads.}
108 #' \item{shiny.minified (defaults to `TRUE`)}{By default
109 #' Whether or not to include Shiny's JavaScript as a minified (`shiny.min.js`)
110 #' or un-minified (`shiny.js`) file. The un-minified version is larger,
111 #' but can be helpful for development and debugging.}
112 #' \item{shiny.port (defaults to a random open port)}{A port number that Shiny will listen on. See
113 #' [runApp()] for more information.}
114 #' \item{shiny.reactlog (defaults to `FALSE`)}{If `TRUE`, enable logging of reactive events,
115 #' which can be viewed later with the [reactlogShow()] function.
116 #' This incurs a substantial performance penalty and should not be used in
117 #' production.}
118 #' \item{shiny.sanitize.errors (defaults to `FALSE`)}{If `TRUE`, then normal errors (i.e.
119 #' errors not wrapped in `safeError`) won't show up in the app; a simple
120 #' generic error message is printed instead (the error and stack trace printed
121 #' to the console remain unchanged). If you want to sanitize errors in general, but you DO want a
122 #' particular error `e` to get displayed to the user, then set this option
123 #' to `TRUE` and use `stop(safeError(e))` for errors you want the
124 #' user to see.}
125 #' \item{shiny.stacktraceoffset (defaults to `TRUE`)}{If `TRUE`, then Shiny's printed stack
126 #' traces will display srcrefs one line above their usual location. This is
127 #' an arguably more intuitive arrangement for casual R users, as the name
128 #' of a function appears next to the srcref where it is defined, rather than
129 #' where it is currently being called from.}
130 #' \item{shiny.suppressMissingContextError (defaults to `FALSE`)}{Normally, invoking a reactive
131 #' outside of a reactive context (or [isolate()]) results in
132 #' an error. If this is `TRUE`, don't error in these cases. This
133 #' should only be used for debugging or demonstrations of reactivity at the
134 #' console.}
135 #' \item{shiny.testmode (defaults to `FALSE`)}{If `TRUE`, then various features for testing Shiny
136 #' applications are enabled.}
137 #' \item{shiny.snapshotsortc (defaults to `FALSE`)}{If `TRUE`, test snapshot keys
138 #' for \pkg{shinytest} will be sorted consistently using the C locale. Snapshots
139 #' retrieved by \pkg{shinytest2} will always sort using the C locale.}
140 #' \item{shiny.trace (defaults to `FALSE`)}{Print messages sent between the R server and the web
141 #' browser client to the R console. This is useful for debugging. Possible
142 #' values are `"send"` (only print messages sent to the client),
143 #' `"recv"` (only print messages received by the server), `TRUE`
144 #' (print all messages), or `FALSE` (default; don't print any of these
145 #' messages).}
146 #' \item{shiny.autoload.r (defaults to `TRUE`)}{If `TRUE`, then the R/
147 #' of a shiny app will automatically be sourced.}
148 #' \item{shiny.useragg (defaults to `TRUE`)}{Set to `FALSE` to prevent PNG rendering via the
149 #' ragg package. See [plotPNG()] for more information.}
150 #' \item{shiny.usecairo (defaults to `TRUE`)}{Set to `FALSE` to prevent PNG rendering via the
151 #' Cairo package. See [plotPNG()] for more information.}
152 #' \item{shiny.devmode (defaults to `NULL`)}{Option to enable Shiny Developer Mode. When set,
153 #' different default `getOption(key)` values will be returned. See [devmode()] for more details.}
154 ### Not documenting as 'shiny.devmode.verbose' is for niche use only
155 # ' \item{shiny.devmode.verbose (defaults to `TRUE`)}{If `TRUE`, will display messages printed
156 # ' about which options are being set. See [devmode()] for more details. }
157 ### (end not documenting 'shiny.devmode.verbose')
158 ### start shiny.client_devmode is primarily for niche, internal shinylive usage
159 # ' \item{shiny.client_devmode (defaults to `FALSE`)}{If `TRUE`, enables client-
160 # ' side devmode features. Currently the primary feature is the client-side
161 # ' error console.}
162 ### end shiny.client_devmode
163 #' \item{shiny.otel.collect (defaults to `Sys.getenv("SHINY_OTEL_COLLECT",
164 #' "all")`)}{Determines how Shiny will interact with OpenTelemetry.
165 #'
166 #' Supported values:
167 #' * `"none"` - No Shiny OpenTelemetry tracing.
168 #' * `"session"` - Adds session start/end spans.
169 #' * `"reactive_update"` - Spans for any synchronous/asynchronous reactive
170 #' update. (Includes `"session"` features).
171 #' * `"reactivity"` - Spans for all reactive expressions and logs for setting
172 #' reactive vals and values. (Includes `"reactive_update"` features). This
173 #' option must be set when creating any reactive objects that should record
174 #' OpenTelemetry spans / logs. See [`withOtelCollect()`] and
175 #' [`localOtelCollect()`] for ways to set this option locally when creating
176 #' your reactive expressions.
177 #' * `"all"` - All Shiny OpenTelemetry tracing. Currently equivalent to
178 #' `"reactivity"`.
179 #'
180 #' This option is useful for debugging and profiling while in production. This
181 #' option will only be useful if the `otelsdk` package is installed and
182 #' `otel::is_tracing_enabled()` returns `TRUE`. Please have any OpenTelemetry
183 #' environment variables set before loading any relevant R packages.
184 #'
185 #' To set this option locally within a specific part of your Shiny
186 #' application, see [`withOtelCollect()`] and [`localOtelCollect()`].}
187 #' \item{shiny.otel.sanitize.errors (defaults to `TRUE`)}{If `TRUE`, fatal and unhandled errors will be sanitized before being sent to the OpenTelemetry backend. The default value of `TRUE` is set to avoid potentially sending sensitive information to the OpenTelemetry backend. If you want the full error message and stack trace to be sent to the OpenTelemetry backend, set this option to `FALSE` or use `safeError(e)`.}
188 #' }
189 #'
190 #'
191 #' @section Scoping for `shinyOptions()`:
192 #'
193 #' There are three levels of scoping for `shinyOptions()`: global,
194 #' application, and session.
195 #'
196 #' The global option set is available by default. Any calls to
197 #' `shinyOptions()` and `getShinyOption()` outside of an app will access the
198 #' global option set.
199 #'
200 #' When a Shiny application is run with [runApp()], the global option set is
201 #' duplicated and the new option set is available at the application level. If
202 #' options are set from `global.R`, `app.R`, `ui.R`, or `server.R` (but
203 #' outside of the server function), then the application-level options will be
204 #' modified.
205 #'
206 #' Each time a user session is started, the application-level option set is
207 #' duplicated, for that session. If the options are set from inside the server
208 #' function, then they will be scoped to the session.
209 #'
210 #' @section Options with `shinyOptions()`:
211 #'
212 #' There are a number of global options that affect Shiny's behavior. These
213 #' can be set globally with `options()` or locally (for a single app) with
214 #' `shinyOptions()`.
215 #'
216 #' \describe{ \item{cache}{A caching object that will be used by
217 #' [renderCachedPlot()]. If not specified, a [cachem::cache_mem()] will be
218 #' used.} }
219 #'
220 #' @param ... Options to set, with the form `name = value`.
221 #' @aliases shiny-options
222 #' @export
223 shinyOptions <- function(...) {
224 newOpts <- list2(...)
225
226 if (length(newOpts) > 0) {
227 # If we're within a session, modify at the session level.
228 session <- getDefaultReactiveDomain()
229 if (!is.null(session)) {
230 # Modify session-level-options
231 session$options <- dropNulls(mergeVectors(session$options, newOpts))
232 return(invisible(session$options))
233 }
234
235 # If not in a session, but we have a currently running app, modify options
236 # at the app level.
237 app_state <- getCurrentAppState()
238 if (!is.null(app_state)) {
239 # Modify app-level options
240 app_state$options <- dropNulls(mergeVectors(app_state$options, newOpts))
241 return(invisible(app_state$options))
242 }
243
244 # If no currently running app, modify global options and return them.
245 .globals$options <- dropNulls(mergeVectors(.globals$options, newOpts))
246 return(invisible(.globals$options))
247 }
248
249 # If not setting any options, just return current option set, visibly.
250
251 session <- getDefaultReactiveDomain()
252 if (!is.null(session)) {
253 return(session$options)
254 }
255
256 app_state <- getCurrentAppState()
257 if (!is.null(app_state)) {
258 return(app_state$options)
259 }
260
261 return(.globals$options)
262 }
263
264
265 # Get specific shiny options and put them in a list, reset those shiny options,
266 # and then return the options list. This should be during the creation of a
267 # shiny app object. This function "consumes" the options when the shinyApp
268 # object is created, so the options won't affect another app that is created
269 # later.
270 #
271 # ==== Example ====
272 # shinyOptions(bookmarkStore = 1234)
273 # # This now returns 1234.
274 # getShinyOption("bookmarkStore")
275 #
276 # # Creating the app captures the bookmarkStore option and clears it.
277 # s <- shinyApp(
278 # fluidPage(verbatimTextOutput("txt")),
279 # function(input, output) {
280 # output$txt <- renderText(getShinyOption("bookmarkStore"))
281 # }
282 # )
283 #
284 # # This now returns NULL.
285 # getShinyOption("bookmarkStore")
286 #
287 # When running the app, the app will display "1234"
288 # runApp(s)
289 #
290 # # After quitting the app, this still returns NULL.
291 # getShinyOption("bookmarkStore")
292 # ==================
293 #
294 # If another app had been created after s was created, but before s was run,
295 # then it would capture the value of "bookmarkStore" at the time of creation.
296 captureAppOptions <- function() {
297 options <- list(
298 appDir = getwd(),
299 bookmarkStore = getShinyOption("bookmarkStore")
300 )
301
302 shinyOptions(appDir = NULL, bookmarkStore = NULL)
303
304 options
305 }
306
307 # Do the inverse of captureAppOptions. This should be called once the app is
308 # started.
309 applyCapturedAppOptions <- function(options) {
310 if (!is.null(options)) {
311 do.call(shinyOptions, options)
312 }
313 }