Debian Codegraph @

R/serializers.R

raw
1 #' Add a function for serializing an input before bookmarking application state
2 #'
3 #' @param inputId Name of the input value.
4 #' @param fun A function that takes the input value and returns a modified
5 #' value. The returned value will be used for the test snapshot.
6 #' @param session A Shiny session object.
7 #'
8 #' @export
9 setSerializer <- function(inputId, fun, session = getDefaultReactiveDomain()) {
10 if (is.null(session)) {
11 stop("setSerializer() needs a session object.")
12 }
13
14 input_impl <- .subset2(session$input, "impl")
15 input_impl$setMeta(inputId, "shiny.serializer", fun)
16 }
17
18
19 # For most types of values, simply return the value unchanged.
20 serializerDefault <- function(value, stateDir) {
21 value
22 }
23
24
25 serializerFileInput <- function(value, stateDir = NULL) {
26 # File inputs can be serialized only if there's a stateDir
27 if (is.null(stateDir)) {
28 return(serializerUnserializable())
29 }
30
31 # value is a data frame. When persisting files, we need to copy the file to
32 # the persistent dir and then strip the original path before saving.
33 newpaths <- file.path(stateDir, basename(value$datapath))
34 file.copy(value$datapath, newpaths, overwrite = TRUE)
35 value$datapath <- basename(newpaths)
36
37 value
38 }
39
40
41 # Return a sentinel value that represents "unserializable". This is applied to
42 # for example, passwords and actionButtons.
43 serializerUnserializable <- function(value, stateDir) {
44 structure(
45 list(),
46 serializable = FALSE
47 )
48 }
49
50 # Is this an "unserializable" sentinel value?
51 isUnserializable <- function(x) {
52 identical(
53 attr(x, "serializable", exact = TRUE),
54 FALSE
55 )
56 }
57
58
59 # Given a reactiveValues object and optional directory for saving state, apply
60 # serializer function to each of the values, and return a list of the returned
61 # values. This function passes stateDir to the serializer functions, so if
62 # stateDir is non-NULL, it can have a side effect of writing values to disk (in
63 # stateDir).
64 serializeReactiveValues <- function(values, exclude, stateDir = NULL) {
65 impl <- .subset2(values, "impl")
66
67 # Get named list where keys and values are the names of inputs; we'll retrieve
68 # actual values later.
69 vals <- isolate(impl$names())
70 vals <- setdiff(vals, exclude)
71 names(vals) <- vals
72
73 # Get values and apply serializer functions
74 vals <- lapply(vals, function(name) {
75 val <- impl$get(name)
76
77 # Get the serializer function for this input value. If none specified, use
78 # the default.
79 serializer_fun <- impl$getMeta(name, "shiny.serializer")
80 if (is.null(serializer_fun))
81 serializer_fun <- serializerDefault
82
83 # Apply serializer function.
84 serializer_fun(val, stateDir)
85 })
86
87 # Filter out any values that were marked as unserializable.
88 vals <- Filter(Negate(isUnserializable), vals)
89 vals
90 }