Debian Codegraph @

R/server-input-handlers.R

raw
1 # Create a Map object for input handlers and register the defaults.
2 # This is assigned in .onLoad time.
3 inputHandlers <- NULL
4 on_load({
5 inputHandlers <- Map$new()
6 })
7
8 #' Register an Input Handler
9 #'
10 #' Adds an input handler for data of this type. When called, Shiny will use the
11 #' function provided to refine the data passed back from the client (after being
12 #' deserialized by jsonlite) before making it available in the `input` variable
13 #' of the `server.R` file.
14 #'
15 #' This function will register the handler for the duration of the R process
16 #' (unless Shiny is explicitly reloaded). For that reason, the `type` used
17 #' should be very specific to this package to minimize the risk of colliding
18 #' with another Shiny package which might use this data type name. We recommend
19 #' the format of "packageName.widgetName". It should be called from the
20 #' package's `.onLoad()` function.
21 #'
22 #' Currently Shiny registers the following handlers: `shiny.matrix`,
23 #' `shiny.number`, and `shiny.date`.
24 #'
25 #' The `type` of a custom Shiny Input widget will be deduced using the
26 #' `getType()` JavaScript function on the registered Shiny inputBinding.
27 #' @param type The type for which the handler should be added --- should be a
28 #' single-element character vector.
29 #' @param fun The handler function. This is the function that will be used to
30 #' parse the data delivered from the client before it is available in the
31 #' `input` variable. The function will be called with the following three
32 #' parameters: \enumerate{ \item{The value of this input as provided by the
33 #' client, deserialized using jsonlite.} \item{The `shinysession` in which the
34 #' input exists.} \item{The name of the input.} }
35 #' @param force If `TRUE`, will overwrite any existing handler without warning.
36 #' If `FALSE`, will throw an error if this class already has a handler
37 #' defined.
38 #' @examples
39 #' \dontrun{
40 #' # Register an input handler which rounds a input number to the nearest integer
41 #' # In a package, this should be called from the .onLoad function.
42 #' registerInputHandler("mypackage.validint", function(x, shinysession, name) {
43 #' if (is.null(x)) return(NA)
44 #' round(x)
45 #' })
46 #'
47 #' ## On the Javascript side, the associated input binding must have a corresponding getType method:
48 #' # getType: function(el) {
49 #' # return "mypackage.validint";
50 #' # }
51 #'
52 #' }
53 #' @seealso [removeInputHandler()] [applyInputHandlers()]
54 #' @export
55 registerInputHandler <- function(type, fun, force=FALSE){
56 if (inputHandlers$containsKey(type) && !force){
57 stop("There is already an input handler for type: ", type)
58 }
59 inputHandlers$set(type, fun)
60 }
61
62 #' Deregister an Input Handler
63 #'
64 #' Removes an Input Handler. Rather than using the previously specified handler
65 #' for data of this type, the default jsonlite serialization will be used.
66 #'
67 #' @param type The type for which handlers should be removed.
68 #' @return The handler previously associated with this `type`, if one
69 #' existed. Otherwise, `NULL`.
70 #' @seealso [registerInputHandler()]
71 #' @export
72 removeInputHandler <- function(type){
73 inputHandlers$remove(type)
74 }
75
76
77 # Apply input handler to a single input value
78 applyInputHandler <- function(name, val, shinysession) {
79 splitName <- strsplit(name, ':')[[1]]
80 if (length(splitName) > 1) {
81 if (!inputHandlers$containsKey(splitName[[2]])) {
82 # No input handler registered for this type
83 stop("No handler registered for type ", name)
84 }
85
86 inputName <- splitName[[1]]
87
88 # Get the function for processing this type of input
89 inputHandler <- inputHandlers$get(splitName[[2]])
90
91 return(inputHandler(val, shinysession, inputName))
92
93 } else if (is.list(val) && is.null(names(val))) {
94 return(unlist(val, recursive = TRUE))
95 } else {
96 return(val)
97 }
98 }
99
100 #' Apply input handlers to raw input values
101 #'
102 #' The purpose of this function is to make it possible for external packages to
103 #' test Shiny inputs. It takes a named list of raw input values, applies input
104 #' handlers to those values, and then returns a named list of the processed
105 #' values.
106 #'
107 #' The raw input values should be in a named list. Some values may have names
108 #' like `"x:shiny.date"`. This function would apply the `"shiny.date"`
109 #' input handler to the value, and then rename the result to `"x"`, in the
110 #' output.
111 #'
112 #' @param inputs A named list of input values.
113 #' @param shinysession A Shiny session object.
114 #'
115 #' @seealso registerInputHandler
116 #' @keywords internal
117 applyInputHandlers <- function(inputs, shinysession = getDefaultReactiveDomain()) {
118 inputs <- mapply(applyInputHandler, names(inputs), inputs,
119 MoreArgs = list(shinysession = shinysession),
120 SIMPLIFY = FALSE)
121
122 # Convert names like "button1:shiny.action" to "button1"
123 names(inputs) <- vapply(
124 names(inputs),
125 function(name) { strsplit(name, ":")[[1]][1] },
126 FUN.VALUE = character(1)
127 )
128
129 inputs
130 }
131
132 on_load({
133 # Takes a list-of-lists and returns a matrix. The lists
134 # must all be the same length. NULL is replaced by NA.
135 registerInputHandler("shiny.matrix", function(data, ...) {
136 if (length(data) == 0)
137 return(matrix(nrow=0, ncol=0))
138
139 m <- matrix(unlist(lapply(data, function(x) {
140 sapply(x, function(y) {
141 ifelse(is.null(y), NA, y)
142 })
143 })), nrow = length(data[[1]]), ncol = length(data))
144 return(m)
145 })
146
147
148 registerInputHandler("shiny.number", function(val, ...){
149 ifelse(is.null(val), NA, val)
150 })
151
152 registerInputHandler("shiny.password", function(val, shinysession, name) {
153 # Mark passwords as not serializable
154 setSerializer(name, serializerUnserializable)
155 val
156 })
157
158 registerInputHandler("shiny.date", function(val, ...){
159 # First replace NULLs with NA, then convert to Date vector
160 datelist <- ifelse(lapply(val, is.null), NA, val)
161
162 res <- NULL
163 tryCatch({
164 res <- as.Date(unlist(datelist))
165 },
166 error = function(e) {
167 # It's possible for client to send a string like "99999-01-01", which
168 # as.Date can't handle.
169 warning(e$message)
170 res <<- as.Date(rep(NA, length(datelist)))
171 }
172 )
173
174 res
175 })
176
177 registerInputHandler("shiny.datetime", function(val, ...){
178 # First replace NULLs with NA, then convert to POSIXct vector
179 times <- lapply(val, function(x) {
180 if (is.null(x)) NA
181 else x
182 })
183 as.POSIXct(unlist(times), origin = "1970-01-01", tz = "UTC")
184 })
185
186 registerInputHandler("shiny.action", function(val, shinysession, name) {
187 # mark up the action button value with a special class so we can recognize it later
188 class(val) <- c("shinyActionButtonValue", class(val))
189 val
190 })
191
192 registerInputHandler("shiny.file", function(val, shinysession, name) {
193 # This function is only used when restoring a Shiny fileInput. When a file is
194 # uploaded the usual way, it takes a different code path and won't hit this
195 # function.
196 if (is.null(val))
197 return(NULL)
198
199 # The data will be a named list of lists; convert to a data frame.
200 val <- as.data.frame(lapply(val, unlist), stringsAsFactors = FALSE)
201
202 # `val$datapath` should be a filename without a path, for security reasons.
203 if (basename(val$datapath) != val$datapath) {
204 stop("Invalid '/' found in file input path.")
205 }
206
207 # Prepend the persistent dir
208 oldfile <- file.path(getCurrentRestoreContext()$dir, val$datapath)
209
210 # Copy the original file to a new temp dir, so that a restored session can't
211 # modify the original.
212 newdir <- file.path(tempdir(), createUniqueId(12))
213 dir.create(newdir)
214 val$datapath <- file.path(newdir, val$datapath)
215 file.copy(oldfile, val$datapath)
216
217 # Need to mark this input value with the correct serializer. When a file is
218 # uploaded the usual way (instead of being restored), this occurs in
219 # session$`@uploadEnd`.
220 setSerializer(name, serializerFileInput)
221
222 snapshotPreprocessInput(name, snapshotPreprocessorFileInput)
223
224 val
225 })
226
227
228 # to be used with !!!answer
229 registerInputHandler("shiny.symbolList", function(val, ...) {
230 if (is.null(val)) {
231 list()
232 } else {
233 lapply(val, as.symbol)
234 }
235 })
236 # to be used with !!answer
237 registerInputHandler("shiny.symbol", function(val, ...) {
238 if (is.null(val) || identical(val, "")) {
239 NULL
240 } else {
241 as.symbol(val)
242 }
243 })
244
245 })