Debian Codegraph @

R/params.R

raw
1
2 knit_params_get <- function(input_lines, params) {
3
4 # read the default parameters and extract them into a named list
5 knit_params <- knitr::knit_params(input_lines)
6 default_params <- list()
7 for (param in knit_params) {
8 default_params[param$name] <- list(param$value)
9 }
10
11 # validate params passed to render
12 if (!is.null(params)) {
13
14 if (identical(params, "ask")) {
15 params <- knit_params_ask(
16 input_lines = input_lines, shiny_args = list(launch.browser = TRUE)
17 )
18 if (is.null(params)) {
19 stop("render parameter configuration canceled")
20 }
21 }
22
23 # verify they are a list
24 if (!is.list(params) || (length(names(params)) != length(params))) {
25 stop("render params argument must be a named list")
26 }
27
28 # verify that all parameters passed are also in the yaml
29 invalid_params <- setdiff(names(params), names(default_params))
30 if (length(invalid_params) > 0) {
31 stop("render params not declared in YAML: ",
32 paste(invalid_params, collapse = ", "))
33 }
34 }
35
36 # merge explicitly provided params with defaults
37 merge_lists(default_params, params, recursive = FALSE)
38 }
39
40 params_label <- function(inputControlFn, param) {
41 label <- ifelse(is.null(param$label), param$name, param$label)
42 if (identical(inputControlFn, shiny::fileInput)) {
43 if (is.character(param$value)) {
44 label <- paste0(label, " (default: ", param$value, ")")
45 }
46 }
47 label
48 }
49
50 params_value_to_ui <- function(inputControlFn, value, showDefault) {
51 if (is.null(showDefault)) {
52 showDefault <- TRUE
53 }
54
55 isNumericInput <- identical(inputControlFn, shiny::numericInput) ||
56 identical(inputControlFn, shiny::sliderInput)
57
58 if (identical(inputControlFn, shiny::fileInput)) {
59 NULL
60 } else if (identical(inputControlFn, shiny::textInput)) {
61 ## TODO: if long input, maybe truncate textInput values for display
62
63 if (showDefault) {
64 classes <- class(value)
65 if ("POSIXct" %in% classes) {
66 as.character(value)
67 } else {
68 value
69 }
70 } else {
71 NULL
72 }
73 } else if (is.null(value)) {
74 # The numerics can't deal with a NULL value, but everything else is fine.
75 if (isNumericInput) {
76 0
77 } else {
78 value
79 }
80 } else {
81 if (showDefault) {
82 ## A type/control that doesn't need special handling; just emit the value.
83 value
84 } else {
85 if (isNumericInput) {
86 0
87 } else if (identical(inputControlFn, shiny::dateInput)) {
88 # Use NA to clear date inputs:
89 # https://github.com/rstudio/shiny/pull/1299
90 NA
91 } else if (identical(inputControlFn, shiny::radioButtons)) {
92 # As suggested in ?radioButtons
93 character(0)
94 } else {
95 NULL
96 }
97 }
98 }
99 }
100
101 params_value_from_ui <- function(inputControlFn, value, uivalue) {
102 if (identical(inputControlFn, shiny::fileInput)) {
103 backup_file_input(uivalue$datapath)
104 } else if (identical(inputControlFn, shiny::textInput)) {
105 classes <- class(value)
106 if ("POSIXct" %in% classes) {
107 if (identical(uivalue, "")) {
108 # show_default: false produces this situation
109 # Empty POSIXct
110 Sys.time()[-1]
111 } else {
112 tryCatch({
113 as.POSIXct(uivalue)
114 }, error = function(e) {
115 # Unparseable time values produce NULL and float to the default.
116 # This happens most frequently when actively editing a date/time.
117 NULL
118 })
119 }
120 } else {
121 uivalue
122 }
123 } else {
124 ## A type/control that doesn't need special handling; just emit the value.
125 uivalue
126 }
127 }
128
129 # Uploaded files will be deleted when the shiny UI is closed, so we need to back
130 # them up to new temp files: https://github.com/rstudio/rmarkdown/issues/919
131 backup_file_input <- function(files) {
132 files2 <- files
133 for (i in seq_along(files)) {
134 dir.create(d <- tempfile())
135 files2[i] <- file.path(d, basename(files[i]))
136 }
137 file.copy(files, files2)
138 files2
139 }
140
141 params_get_input <- function(param) {
142 # Maps between value types and input: XXX
143 default_inputs <- list(
144 logical = "checkbox",
145 Date = "date",
146 ## BUG: shiny does not support datetime selectors
147 ## https://github.com/rstudio/shiny/issues/897
148 ## we ask for string input for now.
149 POSIXct = "datetime",
150 character = "text"
151 )
152 default_inputs$integer <- default_inputs$numeric <- {
153 ## If min/max are specified, use a slider.
154 if (is.null(param$min) || is.null(param$max)) {
155 "numeric"
156 } else {
157 "slider"
158 }
159 }
160
161 input <- param$input
162 if (is.null(input)) {
163 if (!is.null(param$choices)) {
164 ## select for a large number of choices and multiple choices.
165 if (isTRUE(param$multiple)) {
166 input <- "select"
167 } else if (length(param$choices) > 4) {
168 input <- "select"
169 } else {
170 input <- "radio"
171 }
172 } else {
173 ## Not choices. Look at the value type to find what input control we
174 ## should use.
175
176 ## A value might have multiple classes. Try: class(Sys.time())
177 ## Try to find first class listed with a named control.
178 for (c in class(param$value)) {
179 default_input <- default_inputs[[c]]
180 if (!is.null(default_input)) {
181 input <- default_input
182 break
183 }
184 }
185 }
186 }
187 input
188 }
189
190 params_get_control <- function(param) {
191 input <- params_get_input(param)
192 if (is.null(input)) {
193 return(NULL)
194 }
195
196 # Maps between input: XXX and the various Shiny input controls
197 input_controls <- list(
198 checkbox = shiny::checkboxInput,
199 numeric = shiny::numericInput,
200 slider = shiny::sliderInput,
201 date = shiny::dateInput,
202 datetime = shiny::textInput, # placeholder for future datetime picker
203 text = shiny::textInput,
204 password = shiny::passwordInput,
205 file = shiny::fileInput,
206 radio = shiny::radioButtons,
207 select = shiny::selectInput
208 )
209 control <- input_controls[[input]]
210 if (is.null(control)) {
211 stop(paste("could not determine what control to use for parameter", param$name, "with input:", input))
212 }
213 control
214 }
215
216 # Returns true if the parameter can be configurable with Shiny UI elements.
217 params_configurable <- function(param) {
218 inputControlFn <- params_get_control(param)
219 if (is.null(inputControlFn)) {
220 return(FALSE) # no Shiny control
221 }
222 # Some inputs (like selectInput) support the selection of
223 # multiple entries through a "multiple" argument.
224 if (isTRUE(param$multiple)) {
225 return(TRUE)
226 }
227 # sliderInput supports either one or two-value inputs.
228 if (identical(inputControlFn, shiny::sliderInput)) {
229 return(length(param$value) <= 2)
230 }
231 # Other inputs only support singular values.
232 return(length(param$value) <= 1) # multiple values only when multi-input controls
233 }
234
235 # Returns a new empty named list.
236 params_namedList <- function() {
237 empty <- list()
238 names(empty) <- character()
239 empty
240 }
241
242 #' Run a shiny application asking for parameter configuration for the given document.
243 #'
244 #' @param file Path to the R Markdown document with configurable parameters.
245 #' @param input_lines Content of the R Markdown document. If \code{NULL}, the contents of \code{file} will be read.
246 #' @param params A named list of optional parameter overrides used in place of the document defaults.
247 #' @param shiny_args Additional arguments to \code{\link[shiny:runApp]{runApp}}.
248 #' @param save_caption Caption to use use for button that saves/confirms parameters.
249 #' @inheritParams render
250 #' @return named list with overridden parameter names and value.
251 #'
252 #' @export
253 knit_params_ask <- function(file = NULL,
254 input_lines = NULL,
255 params = NULL,
256 shiny_args = NULL,
257 save_caption = "Save",
258 encoding = "UTF-8") {
259
260 if (is.null(input_lines)) {
261 if (is.null(file)) {
262 stop("knit_params_ask must have a non-NULL file or input_lines parameter")
263 }
264 input_lines <- read_utf8(file)
265 }
266
267 knit_params <- knitr::knit_params(input_lines)
268
269 ## Input validation on params (checks shared with render)
270 if (!is.null(params)) {
271 ## Must be a named list
272 if (!is.list(params) || (length(names(params)) != length(params))) {
273 stop("knit_params_ask params argument must be a named list")
274 }
275 ## We do not validate names(params) because the document may have changed
276 ## but we're loading parameters that were configured with an older
277 ## version.
278 }
279
280 ## If we happen to not have any knit_params, just return an empty named list
281 ## and don't fire up the Shiny app.
282 if (length(knit_params) == 0) {
283 return(params_namedList())
284 }
285
286 configurable <- Filter(params_configurable, knit_params)
287 unconfigurable <- Filter(Negate(params_configurable), knit_params)
288
289 ## This set of published values is the raw set that came from the user.
290 ## It does not include those values that cannot be configured or are
291 ## left to use the default.
292 values <- params_namedList()
293
294 server <- function(input, output, session) {
295 param.ui <- function(param) {
296 inputControlFn <- params_get_control(param)
297 inputControlFnFormals <- names(formals(inputControlFn))
298
299 inputId <- param$name
300 label <- params_label(inputControlFn, param)
301
302 arguments = list(
303 inputId = inputId,
304 label = label
305 )
306
307 # We MUST process the "value" name even if it is not present (due to
308 # NULL values).
309 attrib_names <- unique(c(names(param), "value"))
310 lapply(attrib_names, function(name) {
311 if (name %in% c("name", "input", "expr")) {
312 } else if (name == "label") {
313 arguments$label <<- label
314 } else if (name == "value") {
315
316 ## The current value for this parameter is either `params` when
317 ## overridden by our caller or `param$value` otherwise.
318 current_value <- param$value
319 if (!is.null(params)) {
320 override <- params[[param$name]]
321 if (!is.null(override)) {
322 current_value <- override
323 }
324 }
325 # Now, transform into something that the input control can handle.
326 current_value <- params_value_to_ui(inputControlFn, current_value,
327 param$show_default)
328
329 # value maps to either "value" or "selected" depending on the control.
330 if ("value" %in% inputControlFnFormals) {
331 arguments$value <<- current_value
332 } else if ("selected" %in% inputControlFnFormals) {
333 arguments$selected <<- current_value
334 }
335 } else if (name == "show_default") {
336 # No-op
337 } else {
338 ## Not a special field. Blindly promote to the input control.
339 arguments[[name]] <<- if (inherits(param[[name]], 'knit_param_expr')) {
340 param[[name]][['value']]
341 } else param[[name]]
342 }
343 })
344
345 ## This is based on param$value not current_value because we want to
346 ## understand deviation from the report default, not any (optional)
347 ## call-time override.
348 uidefault <- params_value_to_ui(inputControlFn, param$value, param$show_default)
349 hasDefaultValue <- function(value) {
350 identical(uidefault, value)
351 }
352
353 inputControl <- NULL
354 unsupported <- setdiff(names(arguments), inputControlFnFormals)
355 if (length(unsupported) > 0) {
356 inputControl <- shiny::div(class = "form-group",
357 tags$label(class = "control-label",param$name),
358 shiny::div(paste('Cannot customize the parameter "', param$name, '" ',
359 'because the "', params_get_input(param), '" ',
360 'Shiny control does not support: ',
361 paste(unsupported, collapse = ', '), sep = '')))
362 } else {
363 inputControl <- do.call(inputControlFn, arguments)
364 }
365
366 showSelectControl <- NULL
367 selectControl <- NULL
368 selectInputId <- paste0("select_", param$name)
369
370 ## Helper to materialize a "default/customize" control.
371 makeSelectControl <- function(default_name, custom_name) {
372 showSelectControl <<- function(current) {
373 (is.null(current) || identical(current, "default"))
374 }
375 hasDefaultValue <<- function(value) { FALSE }
376 choices <- list()
377 choices[[default_name]] <- "default"
378 choices[[custom_name]] <- "custom"
379 selectControl <<- shiny::selectInput(inputId = selectInputId,
380 label = label,
381 choices = choices)
382 }
383
384 if (is.null(params[[param$name]])) { # prior value; implicit customization
385 ## Dates and times with expressions that mean "now" or "today" are first
386 ## materialized as selects. If the user chooses to customize the field,
387 ## we then show the type-specific picker.
388 if (identical("Sys.time()", param$expr)) {
389 makeSelectControl(paste0("now (", param$value, ")"),
390 "Use a custom time")
391 } else if (identical("Sys.Date()", param$expr)) {
392 makeSelectControl(paste0("today (", param$value, ")"),
393 "Use a custom date")
394 } else if (is.null(param$value)) {
395 # fileInput defaults to null, but for other null values, ask the
396 # user to explicitly choose to override (ie. we cannot use value
397 # comparison).
398 if (!identical(inputControlFn, shiny::fileInput)) {
399 makeSelectControl("Unspecified (NULL)",
400 "Use a custom value")
401 }
402 }
403 }
404
405 output[[paste0("ui_", param$name)]] <- shiny::renderUI({
406 # For most parameters, the selectInputId input will be NULL.
407 if (!is.null(showSelectControl) && showSelectControl(input[[selectInputId]])) {
408 selectControl
409 } else {
410 inputControl
411 }
412 })
413
414 shiny::observe({
415 # A little reactive magic to keep in mind. If you're in one of the
416 # "default/custom" selector scenarios, this will never fire until the
417 # user selects "custom" because the value-producing input control is
418 # not rendered until that point.
419 uivalue <- input[[param$name]]
420 if (is.null(uivalue) || hasDefaultValue(uivalue)) {
421 values[[param$name]] <<- NULL
422 } else {
423 values[[param$name]] <<- params_value_from_ui(inputControlFn, param$value, uivalue)
424 }
425 })
426 }
427
428 lapply(configurable, function(param) {
429 param.ui(param)
430 })
431
432 shiny::observeEvent(input$save, {
433 session$onFlushed(function() {
434 session$close()
435 shiny::stopApp(values)
436 })
437 })
438
439 shiny::observeEvent(input$cancel, {
440 session$onFlushed(function() {
441 session$close()
442 shiny::stopApp(NULL)
443 })
444 })
445 }
446
447 contents <- tags$div(
448 shiny::fluidRow(shiny::column(12, lapply(configurable, function(param) {
449 shiny::uiOutput(paste0("ui_", param$name))
450 }))), class = "container-fluid")
451
452 if (length(unconfigurable) > 0) {
453 skipped <- tags$div(tags$strong("Note:"),
454 "The following parameters cannot be customized:",
455 paste(lapply(unconfigurable, function(param) param$name), collapse = ", "))
456 contents <- shiny::tagAppendChildren(contents, shiny::fluidRow(shiny::column(12, skipped)))
457 }
458 footer <- tags$div(
459 tags$div(
460 shiny::fluidRow(shiny::column(
461 12,
462 shiny::actionButton("save", save_caption, class = "btn-primary navbar-btn pull-right"),
463 shiny::actionButton("cancel","Cancel", class = "navbar-btn pull-right")
464 )),
465 class = "container-fluid"),
466 class = "navbar navbar-default navbar-fixed-bottom")
467
468 style <- tags$style(
469 # Our controls are wiiiiide.
470 ".container-fluid .shiny-input-container { width: auto; }",
471 # Prevent the save/cancel buttons from squashing together.
472 ".navbar button { margin-left: 10px; }",
473 # Style for the navbar footer.
474 # http://getbootstrap.com/components/#navbar-fixed-bottom
475 "body { padding-bottom: 70px; }"
476 )
477 ## Escape is "cancel" and Enter is "save".
478 script <- tags$script(HTML("$(document).keyup(function(e) {\n",
479 "if (e.which == 13) { $('#save').click(); } // enter\n",
480 "if (e.which == 27) { $('#cancel').click(); } // esc\n",
481 "});"
482 ))
483 ui <- shiny::bootstrapPage(
484 tags$head(style, script),
485 contents,
486 footer)
487
488 shiny_app <- shiny::shinyApp(ui = ui, server = server)
489 shiny_args <- merge_lists(list(appDir = shiny_app), shiny_args)
490 do.call(shiny::runApp, shiny_args)
491 }