Debian Codegraph @

R/bookmark-state.R

raw
1 ShinySaveState <- R6Class("ShinySaveState",
2 public = list(
3 input = NULL,
4 exclude = NULL,
5 onSave = NULL, # A callback to invoke during the saving process.
6
7 # These are set not in initialize(), but by external functions that modify
8 # the ShinySaveState object.
9 dir = NULL,
10
11
12 initialize = function(input = NULL, exclude = NULL, onSave = NULL) {
13 self$input <- input
14 self$exclude <- exclude
15 self$onSave <- onSave
16 private$values_ <- new.env(parent = emptyenv())
17 }
18 ),
19
20 active = list(
21 # `values` looks to the outside world like an environment for storing
22 # arbitrary values. Two things to note: (1) This is an environment (instead
23 # of, say, a list) because if the onSave function represents multiple
24 # callback functions (when onBookmark is called multiple times), each
25 # callback can change `values`, and if we used a list, one of the callbacks
26 # could easily obliterate values set by another. This can happen when using
27 # modules that have an onBookmark function. (2) The purpose of the active
28 # binding is to prevent replacing state$values with another arbitrary
29 # object. (Simply locking the binding would prevent all changes to
30 # state$values.)
31 values = function(value) {
32 if (missing(value))
33 return(private$values_)
34
35 if (identical(value, private$values_)) {
36 return(value)
37 } else {
38 stop("Items in `values` can be changed, but `values` itself cannot be replaced.")
39 }
40 }
41 ),
42
43 private = list(
44 values_ = NULL
45 )
46 )
47
48
49 # Save a state to disk. Returns a query string which can be used to restore the
50 # session.
51 saveShinySaveState <- function(state) {
52 id <- createUniqueId(8)
53
54 # A function for saving the state object to disk, given a directory to save
55 # to.
56 saveState <- function(stateDir) {
57 state$dir <- stateDir
58
59 # Allow user-supplied onSave function to do things like add state$values, or
60 # save data to state dir.
61 if (!is.null(state$onSave))
62 isolate(state$onSave(state))
63
64 # Serialize values, possibly saving some extra data to stateDir
65 exclude <- c(state$exclude, "._bookmark_")
66 inputValues <- serializeReactiveValues(state$input, exclude, state$dir)
67 saveRDS(inputValues, file.path(stateDir, "input.rds"))
68
69 # If values were added, save them also.
70 if (length(state$values) != 0)
71 saveRDS(state$values, file.path(stateDir, "values.rds"))
72 }
73
74 # Pass the saveState function to the save interface function, which will
75 # invoke saveState after preparing the directory.
76
77 # Look for a save.interface function. This will be defined by the hosting
78 # environment if it supports bookmarking.
79 saveInterface <- getShinyOption("save.interface", default = NULL)
80
81 if (is.null(saveInterface)) {
82 if (inShinyServer()) {
83 # We're in a version of Shiny Server/Connect that doesn't have
84 # bookmarking support.
85 saveInterface <- function(id, callback) {
86 stop("The hosting environment does not support saved-to-server bookmarking.")
87 }
88
89 } else {
90 # We're running Shiny locally.
91 saveInterface <- saveInterfaceLocal
92 }
93 }
94
95 saveInterface(id, saveState)
96
97 paste0("_state_id_=", encodeURIComponent(id))
98 }
99
100 # Encode the state to a URL. This does not save to disk.
101 encodeShinySaveState <- function(state) {
102 # Allow user-supplied onSave function to do things like add state$values.
103 if (!is.null(state$onSave))
104 isolate(state$onSave(state))
105
106 exclude <- c(state$exclude, "._bookmark_")
107 inputVals <- serializeReactiveValues(state$input, exclude, stateDir = NULL)
108
109 inputVals <- vapply(inputVals,
110 function(x) toJSON(x, strict_atomic = FALSE),
111 character(1),
112 USE.NAMES = TRUE
113 )
114
115 res <- ""
116
117 # If any input values are present, add them.
118 if (length(inputVals) != 0) {
119 res <- paste0(res, "_inputs_&",
120 paste0(
121 encodeURIComponent(names(inputVals)),
122 "=",
123 encodeURIComponent(inputVals),
124 collapse = "&"
125 )
126 )
127 }
128
129 # If 'values' is present, add them as well.
130 if (length(state$values) != 0) {
131 values <- vapply(state$values,
132 function(x) toJSON(x, strict_atomic = FALSE),
133 character(1),
134 USE.NAMES = TRUE
135 )
136
137 res <- paste0(res,
138 if (length(inputVals != 0)) "&", # Add separator if there were inputs
139 "_values_&",
140 paste0(
141 encodeURIComponent(names(values)),
142 "=",
143 encodeURIComponent(values),
144 collapse = "&"
145 )
146 )
147 }
148
149 res
150 }
151
152 RestoreContext <- R6Class("RestoreContext",
153 public = list(
154 # This will be set to TRUE if there's actually a state to restore
155 active = FALSE,
156
157 # This is set to an error message string in case there was an initialization
158 # error. Later, after the app has started on the client, the server can send
159 # this message as a notification on the client.
160 initErrorMessage = NULL,
161
162 # This is a RestoreInputSet for input values. This is a key-value store with
163 # some special handling.
164 input = NULL,
165
166 # Directory for extra files, if restoring from state that was saved to disk.
167 dir = NULL,
168
169 # For values other than input values. These values don't need the special
170 # phandling that's needed for input values, because they're only accessed
171 # from the onRestore function.
172 values = NULL,
173
174 initialize = function(queryString = NULL) {
175 self$reset() # Need this to initialize self$input
176
177 if (!is.null(queryString) && nzchar(queryString)) {
178 tryCatch(
179 withLogErrors({
180 qsValues <- parseQueryString(queryString, nested = TRUE)
181
182 if (!is.null(qsValues[["__subapp__"]]) && qsValues[["__subapp__"]] == 1) {
183 # Ignore subapps in shiny docs
184 self$reset()
185
186 } else if (!is.null(qsValues[["_state_id_"]]) && nzchar(qsValues[["_state_id_"]])) {
187 # If we have a "_state_id_" key, restore from saved state and
188 # ignore other key/value pairs. If not, restore from key/value
189 # pairs in the query string.
190 self$active <- TRUE
191 private$loadStateQueryString(queryString)
192
193 } else {
194 # The query string contains the saved keys and values
195 self$active <- TRUE
196 private$decodeStateQueryString(queryString)
197 }
198 }),
199 error = function(e) {
200 # If there's an error in restoring problem, just reset these values
201 self$reset()
202 self$initErrorMessage <- e$message
203 warning(e$message)
204 }
205 )
206 }
207 },
208
209 reset = function() {
210 self$active <- FALSE
211 self$initErrorMessage <- NULL
212 self$input <- RestoreInputSet$new(list())
213 self$values <- new.env(parent = emptyenv())
214 self$dir <- NULL
215 },
216
217 # Completely replace the state
218 set = function(active = FALSE, initErrorMessage = NULL, input = list(), values = list(), dir = NULL) {
219 # Validate all inputs
220 stopifnot(is.logical(active))
221 stopifnot(is.null(initErrorMessage) || is.character(initErrorMessage))
222 stopifnot(is.list(input))
223 stopifnot(is.list(values))
224 stopifnot(is.null(dir) || is.character(dir))
225
226 self$active <- active
227 self$initErrorMessage <- initErrorMessage
228 self$input <- RestoreInputSet$new(input)
229 self$values <- list2env2(values, parent = emptyenv())
230 self$dir <- dir
231 },
232
233 # This should be called before a restore context is popped off the stack.
234 flushPending = function() {
235 self$input$flushPending()
236 },
237
238
239 # Returns a list representation of the RestoreContext object. This is passed
240 # to the app author's onRestore function. An important difference between
241 # the RestoreContext object and the list is that the former's `input` field
242 # is a RestoreInputSet object, while the latter's `input` field is just a
243 # list.
244 asList = function() {
245 list(
246 input = self$input$asList(),
247 dir = self$dir,
248 values = self$values
249 )
250 }
251 ),
252
253 private = list(
254 # Given a query string with a _state_id_, load saved state with that ID.
255 loadStateQueryString = function(queryString) {
256 values <- parseQueryString(queryString, nested = TRUE)
257 id <- values[["_state_id_"]]
258
259 # Check that id has only alphanumeric chars
260 if (grepl("[^a-zA-Z0-9]", id)) {
261 stop("Invalid state id: ", id)
262 }
263
264 # This function is passed to the loadInterface function; given a
265 # directory, it will load state from that directory
266 loadFun <- function(stateDir) {
267 self$dir <- stateDir
268
269 if (!dirExists(stateDir)) {
270 stop("Bookmarked state directory does not exist.")
271 }
272
273 tryCatch({
274 inputValues <- readRDS(file.path(stateDir, "input.rds"))
275 self$input <- RestoreInputSet$new(inputValues)
276 },
277 error = function(e) {
278 stop("Error reading input values file.")
279 }
280 )
281
282 valuesFile <- file.path(stateDir, "values.rds")
283 if (file.exists(valuesFile)) {
284 tryCatch({
285 self$values <- readRDS(valuesFile)
286 },
287 error = function(e) {
288 stop("Error reading values file.")
289 }
290 )
291 }
292 }
293
294 # Look for a load.interface function. This will be defined by the hosting
295 # environment if it supports bookmarking.
296 loadInterface <- getShinyOption("load.interface", default = NULL)
297
298 if (is.null(loadInterface)) {
299 if (inShinyServer()) {
300 # We're in a version of Shiny Server/Connect that doesn't have
301 # bookmarking support.
302 loadInterface <- function(id, callback) {
303 stop("The hosting environment does not support saved-to-server bookmarking.")
304 }
305
306 } else {
307 # We're running Shiny locally.
308 loadInterface <- loadInterfaceLocal
309 }
310 }
311
312 loadInterface(id, loadFun)
313
314 invisible()
315 },
316
317 # Given a query string with values encoded in it, restore saved state
318 # from those values.
319 decodeStateQueryString = function(queryString) {
320 # Remove leading '?'
321 if (substr(queryString, 1, 1) == '?')
322 queryString <- substr(queryString, 2, nchar(queryString))
323
324 # The "=" after "_inputs_" is optional. Shiny doesn't generate URLs with
325 # "=", but httr always adds "=".
326 inputs_reg <- "(^|&)_inputs_=?(&|$)"
327 values_reg <- "(^|&)_values_=?(&|$)"
328
329 # Error if multiple '_inputs_' or '_values_'. This is needed because
330 # strsplit won't add an entry if the search pattern is at the end of a
331 # string.
332 if (length(gregexpr(inputs_reg, queryString)[[1]]) > 1)
333 stop("Invalid state string: more than one '_inputs_' found")
334 if (length(gregexpr(values_reg, queryString)[[1]]) > 1)
335 stop("Invalid state string: more than one '_values_' found")
336
337 # Look for _inputs_ and store following content in inputStr
338 splitStr <- strsplit(queryString, inputs_reg)[[1]]
339 if (length(splitStr) == 2) {
340 inputStr <- splitStr[2]
341 # Remove any _values_ (and content after _values_) that may come after
342 # _inputs_
343 inputStr <- strsplit(inputStr, values_reg)[[1]][1]
344
345 } else {
346 inputStr <- ""
347 }
348
349 # Look for _values_ and store following content in valueStr
350 splitStr <- strsplit(queryString, values_reg)[[1]]
351 if (length(splitStr) == 2) {
352 valueStr <- splitStr[2]
353 # Remove any _inputs_ (and content after _inputs_) that may come after
354 # _values_
355 valueStr <- strsplit(valueStr, inputs_reg)[[1]][1]
356
357 } else {
358 valueStr <- ""
359 }
360
361
362 inputs <- parseQueryString(inputStr, nested = TRUE)
363 values <- parseQueryString(valueStr, nested = TRUE)
364
365 valuesFromJSON <- function(vals) {
366 varsUnparsed <- c()
367 valsParsed <- mapply(names(vals), vals, SIMPLIFY = FALSE,
368 FUN = function(name, value) {
369 tryCatch(
370 safeFromJSON(value),
371 error = function(e) {
372 varsUnparsed <<- c(varsUnparsed, name)
373 warning("Failed to parse URL parameter \"", name, "\"")
374 }
375 )
376 }
377 )
378 valsParsed[varsUnparsed] <- NULL
379 valsParsed
380 }
381
382 inputs <- valuesFromJSON(inputs)
383 self$input <- RestoreInputSet$new(inputs)
384
385 values <- valuesFromJSON(values)
386 self$values <- list2env2(values, self$values)
387 }
388 )
389 )
390
391
392 # Restore input set. This is basically a key-value store, except for one
393 # important difference: When the user `get()`s a value, the value is marked as
394 # pending; when `flushPending()` is called, those pending values are marked as
395 # used. When a value is marked as used, `get()` will not return it, unless
396 # called with `force=TRUE`. This is to make sure that a particular value can be
397 # restored only within a single call to `withRestoreContext()`. Without this, if
398 # a value is restored in a dynamic UI, it could completely prevent any other
399 # (non- restored) kvalue from being used.
400 RestoreInputSet <- R6Class("RestoreInputSet",
401 private = list(
402 values = NULL,
403 pending = character(0),
404 used = character(0) # Names of values which have been used
405 ),
406
407 public = list(
408 initialize = function(values) {
409 private$values <- list2env2(values, parent = emptyenv())
410 },
411
412 exists = function(name) {
413 exists(name, envir = private$values)
414 },
415
416 # Return TRUE if the value exists and has not been marked as used.
417 available = function(name) {
418 self$exists(name) && !self$isUsed(name)
419 },
420
421 isPending = function(name) {
422 name %in% private$pending
423 },
424
425 isUsed = function(name) {
426 name %in% private$used
427 },
428
429 # Get a value. If `force` is TRUE, get the value without checking whether
430 # has been used, and without marking it as pending.
431 get = function(name, force = FALSE) {
432 if (force)
433 return(private$values[[name]])
434
435 if (!self$available(name))
436 return(NULL)
437
438 # Mark this name as pending. Use unique so that it's not added twice.
439 private$pending <- unique(c(private$pending, name))
440 private$values[[name]]
441 },
442
443 # Take pending names and mark them as used, then clear pending list.
444 flushPending = function() {
445 private$used <- unique(c(private$used, private$pending))
446 private$pending <- character(0)
447 },
448
449 asList = function() {
450 as.list.environment(private$values, all.names = TRUE)
451 }
452 )
453 )
454
455 restoreCtxStack <- NULL
456 on_load({
457 restoreCtxStack <- fastmap::faststack()
458 })
459
460 withRestoreContext <- function(ctx, expr) {
461 restoreCtxStack$push(ctx)
462
463 on.exit({
464 # Mark pending names as used
465 restoreCtxStack$peek()$flushPending()
466 restoreCtxStack$pop()
467 }, add = TRUE)
468
469 force(expr)
470 }
471
472 # Is there a current restore context?
473 hasCurrentRestoreContext <- function() {
474 if (restoreCtxStack$size() > 0)
475 return(TRUE)
476 domain <- getDefaultReactiveDomain()
477 if (!is.null(domain) && !is.null(domain$restoreContext))
478 return(TRUE)
479
480 return(FALSE)
481 }
482
483 # Call to access the current restore context. First look on the restore
484 # context stack, and if not found, then see if there's one on the current
485 # reactive domain. In practice, the only time there will be a restore context
486 # on the stack is when executing the UI function; when executing server code,
487 # the restore context will be attached to the domain/session.
488 getCurrentRestoreContext <- function() {
489 ctx <- restoreCtxStack$peek()
490 if (is.null(ctx)) {
491 domain <- getDefaultReactiveDomain()
492
493 if (is.null(domain) || is.null(domain$restoreContext)) {
494 stop("No restore context found")
495 }
496
497 ctx <- domain$restoreContext
498 }
499 ctx
500 }
501
502 #' Restore an input value
503 #'
504 #' This restores an input value from the current restore context. It should be
505 #' called early on inside of input functions (like [textInput()]).
506 #'
507 #' @param id Name of the input value to restore.
508 #' @param default A default value to use, if there's no value to restore.
509 #'
510 #' @export
511 restoreInput <- function(id, default) {
512 # Need to evaluate `default` in case it contains reactives like input$x. If we
513 # don't, then the calling code won't take a reactive dependency on input$x
514 # when restoring a value.
515 force(default)
516
517 if (!hasCurrentRestoreContext()) {
518 return(default)
519 }
520
521 oldInputs <- getCurrentRestoreContext()$input
522 if (oldInputs$available(id)) {
523 oldInputs$get(id)
524 } else {
525 default
526 }
527 }
528
529 #' Update URL in browser's location bar
530 #'
531 #' This function updates the client browser's query string in the location bar.
532 #' It typically is called from an observer. Note that this will not work in
533 #' Internet Explorer 9 and below.
534 #'
535 #' For `mode = "push"`, only three updates are currently allowed:
536 #' \enumerate{
537 #' \item the query string (format: `?param1=val1&param2=val2`)
538 #' \item the hash (format: `#hash`)
539 #' \item both the query string and the hash
540 #' (format: `?param1=val1&param2=val2#hash`)
541 #' }
542 #'
543 #' In other words, if `mode = "push"`, the `queryString` must start
544 #' with either `?` or with `#`.
545 #'
546 #' A technical curiosity: under the hood, this function is calling the HTML5
547 #' history API (which is where the names for the `mode` argument come from).
548 #' When `mode = "replace"`, the function called is
549 #' `window.history.replaceState(null, null, queryString)`.
550 #' When `mode = "push"`, the function called is
551 #' `window.history.pushState(null, null, queryString)`.
552 #'
553 #' @param queryString The new query string to show in the location bar.
554 #' @param mode When the query string is updated, should the current history
555 #' entry be replaced (default), or should a new history entry be pushed onto
556 #' the history stack? The former should only be used in a live bookmarking
557 #' context. The latter is useful if you want to navigate between states using
558 #' the browser's back and forward buttons. See Examples.
559 #' @param session A Shiny session object.
560 #' @seealso [enableBookmarking()], [getQueryString()]
561 #' @examples
562 #' ## Only run these examples in interactive sessions
563 #' if (interactive()) {
564 #'
565 #' ## App 1: Doing "live" bookmarking
566 #' ## Update the browser's location bar every time an input changes.
567 #' ## This should not be used with enableBookmarking("server"),
568 #' ## because that would create a new saved state on disk every time
569 #' ## the user changes an input.
570 #' enableBookmarking("url")
571 #' shinyApp(
572 #' ui = function(req) {
573 #' fluidPage(
574 #' textInput("txt", "Text"),
575 #' checkboxInput("chk", "Checkbox")
576 #' )
577 #' },
578 #' server = function(input, output, session) {
579 #' observe({
580 #' # Trigger this observer every time an input changes
581 #' reactiveValuesToList(input)
582 #' session$doBookmark()
583 #' })
584 #' onBookmarked(function(url) {
585 #' updateQueryString(url)
586 #' })
587 #' }
588 #' )
589 #'
590 #' ## App 2: Printing the value of the query string
591 #' ## (Use the back and forward buttons to see how the browser
592 #' ## keeps a record of each state)
593 #' shinyApp(
594 #' ui = fluidPage(
595 #' textInput("txt", "Enter new query string"),
596 #' helpText("Format: ?param1=val1&param2=val2"),
597 #' actionButton("go", "Update"),
598 #' hr(),
599 #' verbatimTextOutput("query")
600 #' ),
601 #' server = function(input, output, session) {
602 #' observeEvent(input$go, {
603 #' updateQueryString(input$txt, mode = "push")
604 #' })
605 #' output$query <- renderText({
606 #' query <- getQueryString()
607 #' queryText <- paste(names(query), query,
608 #' sep = "=", collapse=", ")
609 #' paste("Your query string is:\n", queryText)
610 #' })
611 #' }
612 #' )
613 #' }
614 #' @export
615 updateQueryString <- function(queryString, mode = c("replace", "push"),
616 session = getDefaultReactiveDomain()) {
617 mode <- match.arg(mode)
618 session$updateQueryString(queryString, mode)
619 }
620
621 #' Create a button for bookmarking/sharing
622 #'
623 #' A `bookmarkButton` is a [actionButton()] with a default label
624 #' that consists of a link icon and the text "Bookmark...". It is meant to be
625 #' used for bookmarking state.
626 #'
627 #' @inheritParams actionButton
628 #' @param title A tooltip that is shown when the mouse cursor hovers over the
629 #' button.
630 #' @param id An ID for the bookmark button. The only time it is necessary to set
631 #' the ID unless you have more than one bookmark button in your application.
632 #' If you specify an input ID, it should be excluded from bookmarking with
633 #' [setBookmarkExclude()], and you must create an observer that
634 #' does the bookmarking when the button is pressed. See the examples below.
635 #'
636 #' @seealso [enableBookmarking()] for more examples.
637 #'
638 #' @examples
639 #' ## Only run these examples in interactive sessions
640 #' if (interactive()) {
641 #'
642 #' # This example shows how to use multiple bookmark buttons. If you only need
643 #' # a single bookmark button, see examples in ?enableBookmarking.
644 #' ui <- function(request) {
645 #' fluidPage(
646 #' tabsetPanel(id = "tabs",
647 #' tabPanel("One",
648 #' checkboxInput("chk1", "Checkbox 1"),
649 #' bookmarkButton(id = "bookmark1")
650 #' ),
651 #' tabPanel("Two",
652 #' checkboxInput("chk2", "Checkbox 2"),
653 #' bookmarkButton(id = "bookmark2")
654 #' )
655 #' )
656 #' )
657 #' }
658 #' server <- function(input, output, session) {
659 #' # Need to exclude the buttons from themselves being bookmarked
660 #' setBookmarkExclude(c("bookmark1", "bookmark2"))
661 #'
662 #' # Trigger bookmarking with either button
663 #' observeEvent(input$bookmark1, {
664 #' session$doBookmark()
665 #' })
666 #' observeEvent(input$bookmark2, {
667 #' session$doBookmark()
668 #' })
669 #' }
670 #' enableBookmarking(store = "url")
671 #' shinyApp(ui, server)
672 #' }
673 #' @export
674 bookmarkButton <- function(label = "Bookmark...",
675 icon = shiny::icon("link", lib = "glyphicon"),
676 title = "Bookmark this application's state and get a URL for sharing.",
677 ...,
678 id = "._bookmark_")
679 {
680 actionButton(id, label, icon, title = title, ...)
681 }
682
683
684 #' Generate a modal dialog that displays a URL
685 #'
686 #' The modal dialog generated by `urlModal` will display the URL in a
687 #' textarea input, and the URL text will be selected so that it can be easily
688 #' copied. The result from `urlModal` should be passed to the
689 #' [showModal()] function to display it in the browser.
690 #'
691 #' @param url A URL to display in the dialog box.
692 #' @param title A title for the dialog box.
693 #' @param subtitle Text to display underneath URL.
694 #' @export
695 urlModal <- function(url, title = "Bookmarked application link", subtitle = NULL) {
696
697 subtitleTag <- tagList(
698 br(),
699 span(class = "text-muted", subtitle),
700 span(id = "shiny-bookmark-copy-text", class = "text-muted")
701 )
702
703 modalDialog(
704 title = title,
705 easyClose = TRUE,
706 tags$textarea(class = "form-control", rows = "1", style = "resize: none;",
707 readonly = "readonly",
708 url
709 ),
710 subtitleTag,
711 # Need separate show and shown listeners. The show listener sizes the
712 # textarea just as the modal starts to fade in. The 200ms delay is needed
713 # because if we try to resize earlier, it can't calculate the text height
714 # (scrollHeight will be reported as zero). The shown listener selects the
715 # text; it's needed because because selection has to be done after the fade-
716 # in is completed.
717 tags$script(
718 "$('#shiny-modal').
719 one('show.bs.modal', function() {
720 setTimeout(function() {
721 var $textarea = $('#shiny-modal textarea');
722 $textarea.innerHeight($textarea[0].scrollHeight);
723 }, 200);
724 });
725 $('#shiny-modal')
726 .one('shown.bs.modal', function() {
727 $('#shiny-modal textarea').select().focus();
728 });
729 $('#shiny-bookmark-copy-text')
730 .text(function() {
731 if (/Mac/i.test(navigator.userAgent)) {
732 return 'Press \u2318-C to copy.';
733 } else {
734 return 'Press Ctrl-C to copy.';
735 }
736 });
737 "
738 )
739 )
740 }
741
742
743 #' Display a modal dialog for bookmarking
744 #'
745 #' This is a wrapper function for [urlModal()] that is automatically
746 #' called if an application is bookmarked but no other [onBookmark()]
747 #' callback was set. It displays a modal dialog with the bookmark URL, along
748 #' with a subtitle that is appropriate for the type of bookmarking used ("url"
749 #' or "server").
750 #'
751 #' @param url A URL to show in the modal dialog.
752 #' @export
753 showBookmarkUrlModal <- function(url) {
754 store <- getShinyOption("bookmarkStore", default = "")
755 if (store == "url") {
756 subtitle <- "This link stores the current state of this application."
757 } else if (store == "server") {
758 subtitle <- "The current state of this application has been stored on the server."
759 } else {
760 subtitle <- NULL
761 }
762
763 showModal(urlModal(url, subtitle = subtitle))
764 }
765
766 #' Enable bookmarking for a Shiny application
767 #'
768 #' @description
769 #'
770 #' There are two types of bookmarking: saving an application's state to disk on
771 #' the server, and encoding the application's state in a URL. For state that has
772 #' been saved to disk, the state can be restored with the corresponding state
773 #' ID. For URL-encoded state, the state of the application is encoded in the
774 #' URL, and no server-side storage is needed.
775 #'
776 #' URL-encoded bookmarking is appropriate for applications where there not many
777 #' input values that need to be recorded. Some browsers have a length limit for
778 #' URLs of about 2000 characters, and if there are many inputs, the length of
779 #' the URL can exceed that limit.
780 #'
781 #' Saved-on-server bookmarking is appropriate when there are many inputs, or
782 #' when the bookmarked state requires storing files.
783 #'
784 #' @details
785 #'
786 #' For restoring state to work properly, the UI must be a function that takes
787 #' one argument, `request`. In most Shiny applications, the UI is not a
788 #' function; it might have the form `fluidPage(....)`. Converting it to a
789 #' function is as simple as wrapping it in a function, as in
790 #' \code{function(request) \{ fluidPage(....) \}}.
791 #'
792 #' By default, all input values will be bookmarked, except for the values of
793 #' passwordInputs. fileInputs will be saved if the state is saved on a server,
794 #' but not if the state is encoded in a URL.
795 #'
796 #' When bookmarking state, arbitrary values can be stored, by passing a function
797 #' as the `onBookmark` argument. That function will be passed a
798 #' `ShinySaveState` object. The `values` field of the object is a list
799 #' which can be manipulated to save extra information. Additionally, if the
800 #' state is being saved on the server, and the `dir` field of that object
801 #' can be used to save extra information to files in that directory.
802 #'
803 #' For saved-to-server state, this is how the state directory is chosen:
804 #' \itemize{
805 #' \item If running in a hosting environment such as Shiny Server or
806 #' Connect, the hosting environment will choose the directory.
807 #' \item If running an app in a directory with [runApp()], the
808 #' saved states will be saved in a subdirectory of the app called
809 #' shiny_bookmarks.
810 #' \item If running a Shiny app object that is generated from code (not run
811 #' from a directory), the saved states will be saved in a subdirectory of
812 #' the current working directory called shiny_bookmarks.
813 #' }
814 #'
815 #' When used with [shinyApp()], this function must be called before
816 #' `shinyApp()`, or in the `shinyApp()`'s `onStart` function. An
817 #' alternative to calling the `enableBookmarking()` function is to use the
818 #' `enableBookmarking` *argument* for `shinyApp()`. See examples
819 #' below.
820 #'
821 #' @param store Either `"url"`, which encodes all of the relevant values in
822 #' a URL, `"server"`, which saves to disk on the server, or
823 #' `"disable"`, which disables any previously-enabled bookmarking.
824 #'
825 #' @seealso [onBookmark()], [onBookmarked()],
826 #' [onRestore()], and [onRestored()] for registering
827 #' callback functions that are invoked when the state is bookmarked or
828 #' restored.
829 #'
830 #' Also see [updateQueryString()].
831 #'
832 #' @export
833 #' @examples
834 #' ## Only run these examples in interactive R sessions
835 #' if (interactive()) {
836 #'
837 #' # Basic example with state encoded in URL
838 #' ui <- function(request) {
839 #' fluidPage(
840 #' textInput("txt", "Text"),
841 #' checkboxInput("chk", "Checkbox"),
842 #' bookmarkButton()
843 #' )
844 #' }
845 #' server <- function(input, output, session) { }
846 #' enableBookmarking("url")
847 #' shinyApp(ui, server)
848 #'
849 #'
850 #' # An alternative to calling enableBookmarking(): use shinyApp's
851 #' # enableBookmarking argument
852 #' shinyApp(ui, server, enableBookmarking = "url")
853 #'
854 #'
855 #' # Same basic example with state saved to disk
856 #' enableBookmarking("server")
857 #' shinyApp(ui, server)
858 #'
859 #'
860 #' # Save/restore arbitrary values
861 #' ui <- function(req) {
862 #' fluidPage(
863 #' textInput("txt", "Text"),
864 #' checkboxInput("chk", "Checkbox"),
865 #' bookmarkButton(),
866 #' br(),
867 #' textOutput("lastSaved")
868 #' )
869 #' }
870 #' server <- function(input, output, session) {
871 #' vals <- reactiveValues(savedTime = NULL)
872 #' output$lastSaved <- renderText({
873 #' if (!is.null(vals$savedTime))
874 #' paste("Last saved at", vals$savedTime)
875 #' else
876 #' ""
877 #' })
878 #'
879 #' onBookmark(function(state) {
880 #' vals$savedTime <- Sys.time()
881 #' # state is a mutable reference object, and we can add arbitrary values
882 #' # to it.
883 #' state$values$time <- vals$savedTime
884 #' })
885 #' onRestore(function(state) {
886 #' vals$savedTime <- state$values$time
887 #' })
888 #' }
889 #' enableBookmarking(store = "url")
890 #' shinyApp(ui, server)
891 #'
892 #'
893 #' # Usable with dynamic UI (set the slider, then change the text input,
894 #' # click the bookmark button)
895 #' ui <- function(request) {
896 #' fluidPage(
897 #' sliderInput("slider", "Slider", 1, 100, 50),
898 #' uiOutput("ui"),
899 #' bookmarkButton()
900 #' )
901 #' }
902 #' server <- function(input, output, session) {
903 #' output$ui <- renderUI({
904 #' textInput("txt", "Text", input$slider)
905 #' })
906 #' }
907 #' enableBookmarking("url")
908 #' shinyApp(ui, server)
909 #'
910 #'
911 #' # Exclude specific inputs (The only input that will be saved in this
912 #' # example is chk)
913 #' ui <- function(request) {
914 #' fluidPage(
915 #' passwordInput("pw", "Password"), # Passwords are never saved
916 #' sliderInput("slider", "Slider", 1, 100, 50), # Manually excluded below
917 #' checkboxInput("chk", "Checkbox"),
918 #' bookmarkButton()
919 #' )
920 #' }
921 #' server <- function(input, output, session) {
922 #' setBookmarkExclude("slider")
923 #' }
924 #' enableBookmarking("url")
925 #' shinyApp(ui, server)
926 #'
927 #'
928 #' # Update the browser's location bar every time an input changes. This should
929 #' # not be used with enableBookmarking("server"), because that would create a
930 #' # new saved state on disk every time the user changes an input.
931 #' ui <- function(req) {
932 #' fluidPage(
933 #' textInput("txt", "Text"),
934 #' checkboxInput("chk", "Checkbox")
935 #' )
936 #' }
937 #' server <- function(input, output, session) {
938 #' observe({
939 #' # Trigger this observer every time an input changes
940 #' reactiveValuesToList(input)
941 #' session$doBookmark()
942 #' })
943 #' onBookmarked(function(url) {
944 #' updateQueryString(url)
945 #' })
946 #' }
947 #' enableBookmarking("url")
948 #' shinyApp(ui, server)
949 #'
950 #'
951 #' # Save/restore uploaded files
952 #' ui <- function(request) {
953 #' fluidPage(
954 #' sidebarLayout(
955 #' sidebarPanel(
956 #' fileInput("file1", "Choose CSV File", multiple = TRUE,
957 #' accept = c(
958 #' "text/csv",
959 #' "text/comma-separated-values,text/plain",
960 #' ".csv"
961 #' )
962 #' ),
963 #' tags$hr(),
964 #' checkboxInput("header", "Header", TRUE),
965 #' bookmarkButton()
966 #' ),
967 #' mainPanel(
968 #' tableOutput("contents")
969 #' )
970 #' )
971 #' )
972 #' }
973 #' server <- function(input, output) {
974 #' output$contents <- renderTable({
975 #' inFile <- input$file1
976 #' if (is.null(inFile))
977 #' return(NULL)
978 #'
979 #' if (nrow(inFile) == 1) {
980 #' read.csv(inFile$datapath, header = input$header)
981 #' } else {
982 #' data.frame(x = "multiple files")
983 #' }
984 #' })
985 #' }
986 #' enableBookmarking("server")
987 #' shinyApp(ui, server)
988 #'
989 #' }
990 enableBookmarking <- function(store = c("url", "server", "disable")) {
991 store <- match.arg(store)
992 shinyOptions(bookmarkStore = store)
993 }
994
995
996 #' Exclude inputs from bookmarking
997 #'
998 #' This function tells Shiny which inputs should be excluded from bookmarking.
999 #' It should be called from inside the application's server function.
1000 #'
1001 #' This function can also be called from a module's server function, in which
1002 #' case it will exclude inputs with the specified names, from that module. It
1003 #' will not affect inputs from other modules or from the top level of the Shiny
1004 #' application.
1005 #'
1006 #' @param names A character vector containing names of inputs to exclude from
1007 #' bookmarking.
1008 #' @param session A shiny session object.
1009 #' @seealso [enableBookmarking()] for examples.
1010 #' @export
1011 setBookmarkExclude <- function(names = character(0), session = getDefaultReactiveDomain()) {
1012 session$setBookmarkExclude(names)
1013 }
1014
1015
1016 #' Add callbacks for Shiny session bookmarking events
1017 #'
1018 #' @description
1019 #'
1020 #' These functions are for registering callbacks on Shiny session events. They
1021 #' should be called within an application's server function.
1022 #'
1023 #' \itemize{
1024 #' \item `onBookmark` registers a function that will be called just
1025 #' before Shiny bookmarks state.
1026 #' \item `onBookmarked` registers a function that will be called just
1027 #' after Shiny bookmarks state.
1028 #' \item `onRestore` registers a function that will be called when a
1029 #' session is restored, after the server function executes, but before all
1030 #' other reactives, observers and render functions are run.
1031 #' \item `onRestored` registers a function that will be called after a
1032 #' session is restored. This is similar to `onRestore`, but it will be
1033 #' called after all reactives, observers, and render functions run, and
1034 #' after results are sent to the client browser. `onRestored`
1035 #' callbacks can be useful for sending update messages to the client
1036 #' browser.
1037 #' }
1038 #'
1039 #' @details
1040 #'
1041 #' All of these functions return a function which can be called with no
1042 #' arguments to cancel the registration.
1043 #'
1044 #' The callback function that is passed to these functions should take one
1045 #' argument, typically named "state" (for `onBookmark`, `onRestore`,
1046 #' and `onRestored`) or "url" (for `onBookmarked`).
1047 #'
1048 #' For `onBookmark`, the state object has three relevant fields. The
1049 #' `values` field is an environment which can be used to save arbitrary
1050 #' values (see examples). If the state is being saved to disk (as opposed to
1051 #' being encoded in a URL), the `dir` field contains the name of a
1052 #' directory which can be used to store extra files. Finally, the state object
1053 #' has an `input` field, which is simply the application's `input`
1054 #' object. It can be read, but not modified.
1055 #'
1056 #' For `onRestore` and `onRestored`, the state object is a list. This
1057 #' list contains `input`, which is a named list of input values to restore,
1058 #' `values`, which is an environment containing arbitrary values that were
1059 #' saved in `onBookmark`, and `dir`, the name of the directory that
1060 #' the state is being restored from, and which could have been used to save
1061 #' extra files.
1062 #'
1063 #' For `onBookmarked`, the callback function receives a string with the
1064 #' bookmark URL. This callback function should be used to display UI in the
1065 #' client browser with the bookmark URL. If no callback function is registered,
1066 #' then Shiny will by default display a modal dialog with the bookmark URL.
1067 #'
1068 #' @section Modules:
1069 #'
1070 #' These callbacks may also be used in Shiny modules. When used this way, the
1071 #' inputs and values will automatically be namespaced for the module, and the
1072 #' callback functions registered for the module will only be able to see the
1073 #' module's inputs and values.
1074 #'
1075 #' @param fun A callback function which takes one argument.
1076 #' @param session A shiny session object.
1077 #' @seealso enableBookmarking for general information on bookmarking.
1078 #'
1079 #' @examples
1080 #' ## Only run these examples in interactive sessions
1081 #' if (interactive()) {
1082 #'
1083 #' # Basic use of onBookmark and onRestore: This app saves the time in its
1084 #' # arbitrary values, and restores that time when the app is restored.
1085 #' ui <- function(req) {
1086 #' fluidPage(
1087 #' textInput("txt", "Input text"),
1088 #' bookmarkButton()
1089 #' )
1090 #' }
1091 #' server <- function(input, output) {
1092 #' onBookmark(function(state) {
1093 #' savedTime <- as.character(Sys.time())
1094 #' cat("Last saved at", savedTime, "\n")
1095 #' # state is a mutable reference object, and we can add arbitrary values to
1096 #' # it.
1097 #' state$values$time <- savedTime
1098 #' })
1099 #'
1100 #' onRestore(function(state) {
1101 #' cat("Restoring from state bookmarked at", state$values$time, "\n")
1102 #' })
1103 #' }
1104 #' enableBookmarking("url")
1105 #' shinyApp(ui, server)
1106 #'
1107 #'
1108 #'
1109 # This app illustrates two things: saving values in a file using state$dir, and
1110 # using an onRestored callback to call an input updater function. (In real use
1111 # cases, it probably makes sense to save content to a file only if it's much
1112 # larger.)
1113 #' ui <- function(req) {
1114 #' fluidPage(
1115 #' textInput("txt", "Input text"),
1116 #' bookmarkButton()
1117 #' )
1118 #' }
1119 #' server <- function(input, output, session) {
1120 #' lastUpdateTime <- NULL
1121 #'
1122 #' observeEvent(input$txt, {
1123 #' updateTextInput(session, "txt",
1124 #' label = paste0("Input text (Changed ", as.character(Sys.time()), ")")
1125 #' )
1126 #' })
1127 #'
1128 #' onBookmark(function(state) {
1129 #' # Save content to a file
1130 #' messageFile <- file.path(state$dir, "message.txt")
1131 #' cat(as.character(Sys.time()), file = messageFile)
1132 #' })
1133 #'
1134 #' onRestored(function(state) {
1135 #' # Read the file
1136 #' messageFile <- file.path(state$dir, "message.txt")
1137 #' timeText <- readChar(messageFile, 1000)
1138 #'
1139 #' # updateTextInput must be called in onRestored, as opposed to onRestore,
1140 #' # because onRestored happens after the client browser is ready.
1141 #' updateTextInput(session, "txt",
1142 #' label = paste0("Input text (Changed ", timeText, ")")
1143 #' )
1144 #' })
1145 #' }
1146 #' # "server" bookmarking is needed for writing to disk.
1147 #' enableBookmarking("server")
1148 #' shinyApp(ui, server)
1149 #'
1150 #'
1151 #' # This app has a module, and both the module and the main app code have
1152 #' # onBookmark and onRestore functions which write and read state$values$hash. The
1153 #' # module's version of state$values$hash does not conflict with the app's version
1154 #' # of state$values$hash.
1155 #' #
1156 #' # A basic module that captializes text.
1157 #' capitalizerUI <- function(id) {
1158 #' ns <- NS(id)
1159 #' wellPanel(
1160 #' h4("Text captializer module"),
1161 #' textInput(ns("text"), "Enter text:"),
1162 #' verbatimTextOutput(ns("out"))
1163 #' )
1164 #' }
1165 #' capitalizerServer <- function(input, output, session) {
1166 #' output$out <- renderText({
1167 #' toupper(input$text)
1168 #' })
1169 #' onBookmark(function(state) {
1170 #' state$values$hash <- rlang::hash(input$text)
1171 #' })
1172 #' onRestore(function(state) {
1173 #' if (identical(rlang::hash(input$text), state$values$hash)) {
1174 #' message("Module's input text matches hash ", state$values$hash)
1175 #' } else {
1176 #' message("Module's input text does not match hash ", state$values$hash)
1177 #' }
1178 #' })
1179 #' }
1180 #' # Main app code
1181 #' ui <- function(request) {
1182 #' fluidPage(
1183 #' sidebarLayout(
1184 #' sidebarPanel(
1185 #' capitalizerUI("tc"),
1186 #' textInput("text", "Enter text (not in module):"),
1187 #' bookmarkButton()
1188 #' ),
1189 #' mainPanel()
1190 #' )
1191 #' )
1192 #' }
1193 #' server <- function(input, output, session) {
1194 #' callModule(capitalizerServer, "tc")
1195 #' onBookmark(function(state) {
1196 #' state$values$hash <- rlang::hash(input$text)
1197 #' })
1198 #' onRestore(function(state) {
1199 #' if (identical(rlang::hash(input$text), state$values$hash)) {
1200 #' message("App's input text matches hash ", state$values$hash)
1201 #' } else {
1202 #' message("App's input text does not match hash ", state$values$hash)
1203 #' }
1204 #' })
1205 #' }
1206 #' enableBookmarking(store = "url")
1207 #' shinyApp(ui, server)
1208 #' }
1209 #' @export
1210 onBookmark <- function(fun, session = getDefaultReactiveDomain()) {
1211 session$onBookmark(fun)
1212 }
1213
1214 #' @rdname onBookmark
1215 #' @export
1216 onBookmarked <- function(fun, session = getDefaultReactiveDomain()) {
1217 session$onBookmarked(fun)
1218 }
1219
1220 #' @rdname onBookmark
1221 #' @export
1222 onRestore <- function(fun, session = getDefaultReactiveDomain()) {
1223 session$onRestore(fun)
1224 }
1225
1226 #' @rdname onBookmark
1227 #' @export
1228 onRestored <- function(fun, session = getDefaultReactiveDomain()) {
1229 session$onRestored(fun)
1230 }