mirror of
https://github.com/rstudio/shiny.git
synced 2026-01-11 16:08:19 -05:00
Compare commits
86 Commits
v0.14.2
...
feature/ap
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
417f7f7236 | ||
|
|
c1d92c2767 | ||
|
|
3d2f677e2f | ||
|
|
b15cc6cbc0 | ||
|
|
4fbb8a436c | ||
|
|
308b41b8e8 | ||
|
|
516d0cd2ca | ||
|
|
f9d8217f90 | ||
|
|
58ad213a6f | ||
|
|
6ef5c7728e | ||
|
|
58a5fe9a84 | ||
|
|
c633c8b7dd | ||
|
|
e75c99672d | ||
|
|
7faba72ebe | ||
|
|
cbe8fc1bdf | ||
|
|
f66a7660e2 | ||
|
|
5f3159a203 | ||
|
|
76aeda4436 | ||
|
|
fa791cd28c | ||
|
|
d836c68ee5 | ||
|
|
519d90f0a7 | ||
|
|
26400be6f7 | ||
|
|
92ba7e9d54 | ||
|
|
25eafe1e69 | ||
|
|
118a9ca861 | ||
|
|
174a1fe834 | ||
|
|
1e0f3f40a9 | ||
|
|
19623694f5 | ||
|
|
55a16043e1 | ||
|
|
29943b7edd | ||
|
|
a1e2af9533 | ||
|
|
c350e2a668 | ||
|
|
e0868ba2ab | ||
|
|
bcefd1fbd8 | ||
|
|
f5fbad0abf | ||
|
|
95b1a197be | ||
|
|
39169a36f5 | ||
|
|
3b1a409f07 | ||
|
|
accd70d4b4 | ||
|
|
3c7f4b760f | ||
|
|
f7d7ccfd2c | ||
|
|
de98a03887 | ||
|
|
0e11c240cb | ||
|
|
c0a298e484 | ||
|
|
907b9a9862 | ||
|
|
8d70d91cf4 | ||
|
|
6fb86859ce | ||
|
|
fe733b319f | ||
|
|
08b58f3055 | ||
|
|
9f6659f526 | ||
|
|
d28397df93 | ||
|
|
2e1c37146b | ||
|
|
903adc8f97 | ||
|
|
fc7f454382 | ||
|
|
ef35fc63a1 | ||
|
|
52a193b183 | ||
|
|
dad401a6ec | ||
|
|
ec3f8118db | ||
|
|
cfc0194c00 | ||
|
|
dd28f52301 | ||
|
|
9dcbd532e6 | ||
|
|
16b4a2cad2 | ||
|
|
bd9d8a035a | ||
|
|
d55ffb0212 | ||
|
|
e76ddfd005 | ||
|
|
59145a3b40 | ||
|
|
c993f5343b | ||
|
|
b62acec5ee | ||
|
|
b34ab9cdd5 | ||
|
|
e0a8ab852e | ||
|
|
bd5ebd0e41 | ||
|
|
661e21d25b | ||
|
|
dc69a2bc94 | ||
|
|
e6fec6b27d | ||
|
|
27b92f9838 | ||
|
|
3446def4dd | ||
|
|
2700206715 | ||
|
|
fdfc6f70f3 | ||
|
|
065c288edb | ||
|
|
3121d2c23e | ||
|
|
7cd3bb524c | ||
|
|
6b8cc97779 | ||
|
|
b7112a1edd | ||
|
|
28965b7356 | ||
|
|
bd3aa28416 | ||
|
|
9fed4ce24c |
@@ -1,10 +1,38 @@
|
||||
|
||||
We welcome contributions to the **shiny** package. To submit a contribution:
|
||||
|
||||
1. [Fork](https://github.com/rstudio/shiny/fork) the repository and make your changes.
|
||||
|
||||
2. Ensure that you have signed the [individual](http://www.rstudio.com/wp-content/uploads/2014/06/RStudioIndividualContributorAgreement.pdf) or [corporate](http://www.rstudio.com/wp-content/uploads/2014/06/RStudioCorporateContributorAgreement.pdf) contributor agreement as appropriate. You can send the signed copy to jj@rstudio.com.
|
||||
2. If the change is non-trivial, ensure that you have signed the [individual](http://www.rstudio.com/wp-content/uploads/2014/06/RStudioIndividualContributorAgreement.pdf) or [corporate](http://www.rstudio.com/wp-content/uploads/2014/06/RStudioCorporateContributorAgreement.pdf) contributor agreement as appropriate. You can send the signed copy to jj@rstudio.com. For trivial changes (like typo fixes), a contributor agreement is not needed.
|
||||
|
||||
3. Submit a [pull request](https://help.github.com/articles/using-pull-requests).
|
||||
|
||||
We'll try to be as responsive as possible in reviewing and accepting pull requests. We appreciate your contributions!
|
||||
We generally do not merge pull requests that update included web libraries (such as Bootstrap or jQuery) because it is difficult for us to verify that the update is done correctly; we prefer to update these libraries ourselves.
|
||||
|
||||
|
||||
## How to make changes
|
||||
|
||||
Before you submit a pull request, please do the following:
|
||||
|
||||
* Add an entry to NEWS.md concisely describing what you changed.
|
||||
|
||||
* If appropriate, add unit tests in the tests/ directory.
|
||||
|
||||
* If you made any changes to the JavaScript files in the srcjs/ directory, make sure you build the output JavaScript files. See tools/README.md file for information on using the build system.
|
||||
|
||||
* Run Build->Check Package in the RStudio IDE, or `devtools::check()`, to make sure your change did not add any messages, warnings, or errors.
|
||||
|
||||
Doing these things will make it easier for the Shiny development team to evaluate your pull request. Even so, we may still decide to modify your code or even not merge it at all. Factors that may prevent us from merging the pull request include:
|
||||
|
||||
* breaking backward compatibility
|
||||
* adding a feature that we do not consider relevant for Shiny
|
||||
* is hard to understand
|
||||
* is hard to maintain in the future
|
||||
* is computationally expensive
|
||||
* is not intuitive for people to use
|
||||
|
||||
We will try to be responsive and provide feedback in case we decide not to merge your pull request.
|
||||
|
||||
|
||||
## Filing issues
|
||||
|
||||
If you find a bug in Shiny, you can also [file an issue](https://github.com/rstudio/shiny/issues/new). Please provide as much relevant information as you can, and include a minimal reproducible example if possible.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Package: shiny
|
||||
Type: Package
|
||||
Title: Web Application Framework for R
|
||||
Version: 0.14.2
|
||||
Version: 1.0.0
|
||||
Authors@R: c(
|
||||
person("Winston", "Chang", role = c("aut", "cre"), email = "winston@rstudio.com"),
|
||||
person("Joe", "Cheng", role = "aut", email = "joe@rstudio.com"),
|
||||
@@ -79,7 +79,8 @@ Suggests:
|
||||
knitr (>= 1.6),
|
||||
markdown,
|
||||
rmarkdown,
|
||||
ggplot2
|
||||
ggplot2,
|
||||
magrittr
|
||||
URL: http://shiny.rstudio.com
|
||||
BugReports: https://github.com/rstudio/shiny/issues
|
||||
Collate:
|
||||
|
||||
14
NAMESPACE
14
NAMESPACE
@@ -2,18 +2,24 @@
|
||||
|
||||
S3method("$",reactivevalues)
|
||||
S3method("$",session_proxy)
|
||||
S3method("$",shinyapi)
|
||||
S3method("$",shinyoutput)
|
||||
S3method("$<-",reactivevalues)
|
||||
S3method("$<-",session_proxy)
|
||||
S3method("$<-",shinyapi)
|
||||
S3method("$<-",shinyoutput)
|
||||
S3method("[",reactivevalues)
|
||||
S3method("[",shinyapi)
|
||||
S3method("[",shinyoutput)
|
||||
S3method("[<-",reactivevalues)
|
||||
S3method("[<-",shinyapi)
|
||||
S3method("[<-",shinyoutput)
|
||||
S3method("[[",reactivevalues)
|
||||
S3method("[[",session_proxy)
|
||||
S3method("[[",shinyapi)
|
||||
S3method("[[",shinyoutput)
|
||||
S3method("[[<-",reactivevalues)
|
||||
S3method("[[<-",shinyapi)
|
||||
S3method("[[<-",shinyoutput)
|
||||
S3method("names<-",reactivevalues)
|
||||
S3method(as.list,reactivevalues)
|
||||
@@ -61,6 +67,7 @@ export(dataTableOutput)
|
||||
export(dateInput)
|
||||
export(dateRangeInput)
|
||||
export(dblclickOpts)
|
||||
export(debounce)
|
||||
export(dialogViewer)
|
||||
export(div)
|
||||
export(downloadButton)
|
||||
@@ -193,6 +200,11 @@ export(runUrl)
|
||||
export(safeError)
|
||||
export(selectInput)
|
||||
export(selectizeInput)
|
||||
export(serveCSV)
|
||||
export(serveJSON)
|
||||
export(servePlot)
|
||||
export(serveRaw)
|
||||
export(serveText)
|
||||
export(serverInfo)
|
||||
export(setBookmarkExclude)
|
||||
export(setProgress)
|
||||
@@ -229,6 +241,7 @@ export(tags)
|
||||
export(textAreaInput)
|
||||
export(textInput)
|
||||
export(textOutput)
|
||||
export(throttle)
|
||||
export(titlePanel)
|
||||
export(uiOutput)
|
||||
export(updateActionButton)
|
||||
@@ -265,3 +278,4 @@ import(httpuv)
|
||||
import(methods)
|
||||
import(mime)
|
||||
import(xtable)
|
||||
importFrom(utils,write.csv)
|
||||
|
||||
66
NEWS.md
66
NEWS.md
@@ -1,3 +1,69 @@
|
||||
shiny 1.0.0
|
||||
===========
|
||||
|
||||
Shiny has reached a milestone: version 1.0.0! In the last year, we've added two major features that we considered essential for a 1.0.0 release: bookmarking, and support for testing Shiny applications. As usual, this version of Shiny also includes many minor features and bug fixes.
|
||||
|
||||
Here are some highlights from this release. For more details, see the full changelog below.
|
||||
|
||||
## Support for testing Shiny applications
|
||||
|
||||
Shiny now supports automated testing of applications, with the [shinytest](https://github.com/rstudio/shinytest) package. Shinytest has not yet been released on CRAN, but will be soon. ([#18](https://github.com/rstudio/shiny/issues/18), [#1464](https://github.com/rstudio/shiny/pull/1464))
|
||||
|
||||
## Debounce/throttle reactives
|
||||
|
||||
Now there's an official way to slow down reactive values and expressions that invalidate too quickly. Pass a reactive expression to the new `debounce` or `throttle` function, and get back a modified reactive expression that doesn't invalidate as often. ([#1510](https://github.com/rstudio/shiny/pull/1510))
|
||||
|
||||
## Full changelog
|
||||
|
||||
### Breaking changes
|
||||
|
||||
* Added a new `placeholder` argument to `verbatimTextOutput()`. The default is `FALSE`, which means that, if there is no content for this output, no representation of this slot will be made in the UI. Previsouly, even if there was no content, you'd see an empty rectangle in the UI that served as a placeholder. You can set `placeholder = TRUE` to revert back to that look. ([#1480](https://github.com/rstudio/shiny/pull/1480))
|
||||
|
||||
### New features
|
||||
|
||||
* Added support for testing Shiny applications with the shinytest package. ([#18](https://github.com/rstudio/shiny/issues/18), [#1464](https://github.com/rstudio/shiny/pull/1464))
|
||||
|
||||
* Added `debounce` and `throttle` functions, to control the rate at which reactive values and expressions invalidate. ([#1510](https://github.com/rstudio/shiny/pull/1510))
|
||||
|
||||
### Minor new features and improvements
|
||||
|
||||
* Addressed [#1486](https://github.com/rstudio/shiny/issues/1486) by adding a new argument to `observeEvent` and `eventReactive`, called `ignoreInit` (defaults to `FALSE` for backwards compatibility). When set to `TRUE`, the action (i.e. the second argument: `handlerExpr` and `valueExpr`, respectively) will not be triggered when the observer/reactive is first created/initialized. In other words, `ignoreInit = TRUE` ensures that the `observeEvent` (or `eventReactive`) is *never* run right away. For more info, see the documentation (`?observeEvent`). ([#1494](https://github.com/rstudio/shiny/pull/1494))
|
||||
|
||||
* Added a new argument to `observeEvent` called `once`. When set to `TRUE`, it results in the observer being destroyed (stop observing) after the first time that `handlerExpr` is run (i.e. `once = TRUE` guarantees that the observer only runs, at most, once). For more info, see the documentation (`?observeEvent`). ([#1494](https://github.com/rstudio/shiny/pull/1494))
|
||||
|
||||
* Addressed [#1358](https://github.com/rstudio/shiny/issues/1358): more informative error message when calling `runApp()` inside of an app's app.R (or inside ui.R or server.R). ([#1482](https://github.com/rstudio/shiny/pull/1482))
|
||||
|
||||
* Added a more descriptive JS warning for `insertUI()` when the selector argument does not match anything in DOM. ([#1488](https://github.com/rstudio/shiny/pull/1488))
|
||||
|
||||
* Added support for injecting JavaScript code when the `shiny.testmode` option is set to `TRUE`. This makes it possible to record test events interactively. ([#1464](https://github.com/rstudio/shiny/pull/1464))
|
||||
|
||||
* Added ability through arguments to the `a` tag function called inside `downloadButton()` and `downloadLink()`. Closes [#986](https://github.com/rstudio/shiny/issues/986). ([#1492](https://github.com/rstudio/shiny/pulls/1492))
|
||||
|
||||
* Implemented [#1512](https://github.com/rstudio/shiny/issues/1512): added a `userData` environment to `session`, for storing arbitrary session-related variables. Generally, session-scoped variables are created just by declaring normal variables that are local to the Shiny server function, but `session$userData` may be more convenient for some advanced scenarios. ([#1513](https://github.com/rstudio/shiny/pull/1513))
|
||||
|
||||
* Relaxed naming requirements for `addResourcePath()` (the first character no longer needs to be a letter). ([#1529](https://github.com/rstudio/shiny/pull/1529))
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* Fixed [#969](https://github.com/rstudio/shiny/issues/969): allow navbarPage's `fluid` param to control both containers. ([#1481](https://github.com/rstudio/shiny/pull/1481))
|
||||
|
||||
* Fixed [#1438](https://github.com/rstudio/shiny/issues/1438): `unbindAll()` should not be called when inserting content with `insertUI()` ([#1449](https://github.com/rstudio/shiny/pull/1449))
|
||||
|
||||
* Fixed bug causing `<meta>` tags associated with HTML dependencies of Shiny R Markdown files to be rendered incorrectly. ([#1463](https://github.com/rstudio/shiny/pull/1463))
|
||||
|
||||
* Fixed [#1359](https://github.com/rstudio/shiny/issues/1359): `shinyApp()` options argument ignored when passed to `runApp()`. ([#1483](https://github.com/rstudio/shiny/pull/1483))
|
||||
|
||||
* Fixed [#117](https://github.com/rstudio/shiny/issues/117): Reactive expressions now release references to cached values as soon as they are invalidated, potentially making those cached values eligible for garbage collection sooner. Previously, this would not occur until the next cached value was calculated and stored. ([#1504](https://github.com/rstudio/shiny/pull/1504/files))
|
||||
|
||||
* Fixed [#1013](https://github.com/rstudio/shiny/issues/1013): `flushReact` should be called after app loads. Observers set up outside of server functions were not running until after the first user connects. ([#1503](https://github.com/rstudio/shiny/pull/1503))
|
||||
|
||||
* Fixed [#1453](https://github.com/rstudio/shiny/issues/1453): When using a modal dialog with `easyClose=TRUE` in a Shiny gadget, pressing Esc would close both the modal and the gadget. Now pressing Esc only closes the modal. ([#1523](https://github.com/rstudio/shiny/pull/1523))
|
||||
|
||||
### Library updates
|
||||
|
||||
* Updated to Font Awesome 4.7.0.
|
||||
|
||||
|
||||
shiny 0.14.2
|
||||
============
|
||||
|
||||
|
||||
13
R/app.R
13
R/app.R
@@ -20,9 +20,11 @@
|
||||
#' @param onStart A function that will be called before the app is actually run.
|
||||
#' This is only needed for \code{shinyAppObj}, since in the \code{shinyAppDir}
|
||||
#' case, a \code{global.R} file can be used for this purpose.
|
||||
#' @param options Named options that should be passed to the `runApp` call. You
|
||||
#' can also specify \code{width} and \code{height} parameters which provide a
|
||||
#' hint to the embedding environment about the ideal height/width for the app.
|
||||
#' @param options Named options that should be passed to the \code{runApp} call
|
||||
#' (these can be any of the following: "port", "launch.browser", "host", "quiet",
|
||||
#' "display.mode" and "test.mode"). You can also specify \code{width} and
|
||||
#' \code{height} parameters which provide a hint to the embedding environment
|
||||
#' about the ideal height/width for the app.
|
||||
#' @param uiPattern A regular expression that will be applied to each \code{GET}
|
||||
#' request to determine whether the \code{ui} should be used to handle the
|
||||
#' request. Note that the entire request path must match the regular
|
||||
@@ -39,6 +41,8 @@
|
||||
#' @examples
|
||||
#' ## Only run this example in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' shinyApp(
|
||||
#' ui = fluidPage(
|
||||
#' numericInput("n", "n", 1),
|
||||
@@ -373,7 +377,8 @@ is.shiny.appobj <- function(x) {
|
||||
print.shiny.appobj <- function(x, ...) {
|
||||
opts <- x$options %OR% list()
|
||||
opts <- opts[names(opts) %in%
|
||||
c("port", "launch.browser", "host", "quiet", "display.mode")]
|
||||
c("port", "launch.browser", "host", "quiet",
|
||||
"display.mode", "test.mode")]
|
||||
|
||||
args <- c(list(x), opts)
|
||||
|
||||
|
||||
@@ -342,26 +342,10 @@ RestoreContext <- R6Class("RestoreContext",
|
||||
}
|
||||
|
||||
|
||||
inputs <- parseQueryString(inputStr, nested = TRUE)
|
||||
values <- parseQueryString(valueStr, nested = TRUE)
|
||||
inputs <- parseQueryStringJSON(inputStr, nested = TRUE)
|
||||
values <- parseQueryStringJSON(valueStr, nested = TRUE)
|
||||
|
||||
valuesFromJSON <- function(vals) {
|
||||
mapply(names(vals), vals, SIMPLIFY = FALSE,
|
||||
FUN = function(name, value) {
|
||||
tryCatch(
|
||||
jsonlite::fromJSON(value),
|
||||
error = function(e) {
|
||||
stop("Failed to parse URL parameter \"", name, "\"")
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
inputs <- valuesFromJSON(inputs)
|
||||
self$input <- RestoreInputSet$new(inputs)
|
||||
|
||||
values <- valuesFromJSON(values)
|
||||
self$values <- list2env2(values, self$values)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -277,6 +277,7 @@ titlePanel <- function(title, windowTitle=title) {
|
||||
#' @examples
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' # Define UI
|
||||
#' ui <- fluidPage(
|
||||
@@ -442,6 +443,7 @@ inputPanel <- function(...) {
|
||||
#' @examples
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' # Server code used for all examples
|
||||
#' server <- function(input, output) {
|
||||
|
||||
@@ -342,10 +342,18 @@ navbarPage <- function(title,
|
||||
tabs <- list(...)
|
||||
tabset <- buildTabset(tabs, "nav navbar-nav", NULL, id, selected)
|
||||
|
||||
# function to return plain or fluid class name
|
||||
className <- function(name) {
|
||||
if (fluid)
|
||||
paste(name, "-fluid", sep="")
|
||||
else
|
||||
name
|
||||
}
|
||||
|
||||
# built the container div dynamically to support optional collapsibility
|
||||
if (collapsible) {
|
||||
navId <- paste("navbar-collapse-", p_randomInt(1000, 10000), sep="")
|
||||
containerDiv <- div(class="container",
|
||||
containerDiv <- div(class=className("container"),
|
||||
div(class="navbar-header",
|
||||
tags$button(type="button", class="navbar-toggle collapsed",
|
||||
`data-toggle`="collapse", `data-target`=paste0("#", navId),
|
||||
@@ -359,7 +367,7 @@ navbarPage <- function(title,
|
||||
div(class="navbar-collapse collapse", id=navId, tabset$navList)
|
||||
)
|
||||
} else {
|
||||
containerDiv <- div(class="container",
|
||||
containerDiv <- div(class=className("container"),
|
||||
div(class="navbar-header",
|
||||
span(class="navbar-brand", pageTitle)
|
||||
),
|
||||
@@ -367,14 +375,6 @@ navbarPage <- function(title,
|
||||
)
|
||||
}
|
||||
|
||||
# function to return plain or fluid class name
|
||||
className <- function(name) {
|
||||
if (fluid)
|
||||
paste(name, "-fluid", sep="")
|
||||
else
|
||||
name
|
||||
}
|
||||
|
||||
# build the main tab content div
|
||||
contentDiv <- div(class=className("container"))
|
||||
if (!is.null(header))
|
||||
@@ -935,21 +935,34 @@ textOutput <- function(outputId, container = if (inline) span else div, inline =
|
||||
#' Render a reactive output variable as verbatim text within an
|
||||
#' application page. The text will be included within an HTML \code{pre} tag.
|
||||
#' @param outputId output variable to read the value from
|
||||
#' @param placeholder if the output is empty or \code{NULL}, should an empty
|
||||
#' rectangle be displayed to serve as a placeholder? (does not affect
|
||||
#' behavior when the the output in nonempty)
|
||||
#' @return A verbatim text output element that can be included in a panel
|
||||
#' @details Text is HTML-escaped prior to rendering. This element is often used
|
||||
#' with the \link{renderPrint} function to preserve fixed-width formatting
|
||||
#' of printed objects.
|
||||
#' with the \link{renderPrint} function to preserve fixed-width formatting
|
||||
#' of printed objects.
|
||||
#' @examples
|
||||
#' mainPanel(
|
||||
#' h4("Summary"),
|
||||
#' verbatimTextOutput("summary"),
|
||||
#'
|
||||
#' h4("Observations"),
|
||||
#' tableOutput("view")
|
||||
#' )
|
||||
#' ## Only run this example in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' shinyApp(
|
||||
#' ui = basicPage(
|
||||
#' textInput("txt", "Enter the text to display below:"),
|
||||
#' verbatimTextOutput("default"),
|
||||
#' verbatimTextOutput("placeholder", placeholder = TRUE)
|
||||
#' ),
|
||||
#' server = function(input, output) {
|
||||
#' output$default <- renderText({ input$txt })
|
||||
#' output$placeholder <- renderText({ input$txt })
|
||||
#' }
|
||||
#' )
|
||||
#' }
|
||||
#' @export
|
||||
verbatimTextOutput <- function(outputId) {
|
||||
textOutput(outputId, container = pre)
|
||||
verbatimTextOutput <- function(outputId, placeholder = FALSE) {
|
||||
pre(id = outputId,
|
||||
class = paste(c("shiny-text-output", if (!placeholder) "noplaceholder"),
|
||||
collapse = " ")
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1123,7 +1136,7 @@ imageOutput <- function(outputId, width = "100%", height="400px",
|
||||
#' same \code{id} to disappear.
|
||||
#' @inheritParams textOutput
|
||||
#' @note The arguments \code{clickId} and \code{hoverId} only work for R base
|
||||
#' graphics (see the \pkg{\link{graphics}} package). They do not work for
|
||||
#' graphics (see the \pkg{\link[graphics:graphics-package]{graphics}} package). They do not work for
|
||||
#' \pkg{\link[grid:grid-package]{grid}}-based graphics, such as \pkg{ggplot2},
|
||||
#' \pkg{lattice}, and so on.
|
||||
#'
|
||||
@@ -1421,6 +1434,7 @@ uiOutput <- htmlOutput
|
||||
#' is assigned to.
|
||||
#' @param label The label that should appear on the button.
|
||||
#' @param class Additional CSS classes to apply to the tag, if any.
|
||||
#' @param ... Other arguments to pass to the container tag function.
|
||||
#'
|
||||
#' @examples
|
||||
#' \dontrun{
|
||||
@@ -1443,23 +1457,25 @@ uiOutput <- htmlOutput
|
||||
#' @export
|
||||
downloadButton <- function(outputId,
|
||||
label="Download",
|
||||
class=NULL) {
|
||||
class=NULL, ...) {
|
||||
aTag <- tags$a(id=outputId,
|
||||
class=paste('btn btn-default shiny-download-link', class),
|
||||
href='',
|
||||
target='_blank',
|
||||
download=NA,
|
||||
icon("download"),
|
||||
label)
|
||||
label, ...)
|
||||
}
|
||||
|
||||
#' @rdname downloadButton
|
||||
#' @export
|
||||
downloadLink <- function(outputId, label="Download", class=NULL) {
|
||||
downloadLink <- function(outputId, label="Download", class=NULL, ...) {
|
||||
tags$a(id=outputId,
|
||||
class=paste(c('shiny-download-link', class), collapse=" "),
|
||||
href='',
|
||||
target='_blank',
|
||||
label)
|
||||
download=NA,
|
||||
label, ...)
|
||||
}
|
||||
|
||||
|
||||
@@ -1527,7 +1543,7 @@ icon <- function(name, class = NULL, lib = "font-awesome") {
|
||||
# font-awesome needs an additional dependency (glyphicon is in bootstrap)
|
||||
if (lib == "font-awesome") {
|
||||
htmlDependencies(iconTag) <- htmlDependency(
|
||||
"font-awesome", "4.6.3", c(href="shared/font-awesome"),
|
||||
"font-awesome", "4.7.0", c(href="shared/font-awesome"),
|
||||
stylesheet = "css/font-awesome.min.css"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
#' @param width Width in pixels.
|
||||
#' @param height Height in pixels.
|
||||
#' @param res Resolution in pixels per inch. This value is passed to
|
||||
#' \code{\link{png}}. Note that this affects the resolution of PNG rendering in
|
||||
#' \code{\link[grDevices]{png}}. Note that this affects the resolution of PNG rendering in
|
||||
#' R; it won't change the actual ppi of the browser.
|
||||
#' @param ... Arguments to be passed through to \code{\link[grDevices]{png}}.
|
||||
#' These can be used to set the width, height, background color, etc.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#' \item \code{yy} Year without century (12)
|
||||
#' \item \code{yyyy} Year with century (2012)
|
||||
#' \item \code{mm} Month number, with leading zero (01-12)
|
||||
#' \item \code{m} Month number, without leading zero (01-12)
|
||||
#' \item \code{m} Month number, without leading zero (1-12)
|
||||
#' \item \code{M} Abbreviated month name
|
||||
#' \item \code{MM} Full month name
|
||||
#' \item \code{dd} Day of month with leading zero
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#' \item \code{yy} Year without century (12)
|
||||
#' \item \code{yyyy} Year with century (2012)
|
||||
#' \item \code{mm} Month number, with leading zero (01-12)
|
||||
#' \item \code{m} Month number, without leading zero (01-12)
|
||||
#' \item \code{m} Month number, without leading zero (1-12)
|
||||
#' \item \code{M} Abbreviated month name
|
||||
#' \item \code{MM} Full month name
|
||||
#' \item \code{dd} Day of month with leading zero
|
||||
|
||||
@@ -15,7 +15,12 @@
|
||||
#'
|
||||
#' @inheritParams textInput
|
||||
#' @param choices List of values to select from. If elements of the list are
|
||||
#' named then that name rather than the value is displayed to the user.
|
||||
#' named, then that name rather than the value is displayed to the user.
|
||||
#' This can also be a named list whose elements are (either named or
|
||||
#' unnamed) lists or vectors. If this is the case, the outermost names
|
||||
#' will be used as the "optgroup" label for the elements in the respective
|
||||
#' sublist. This allows you to group and label similar choices. See the
|
||||
#' example section for a small demo of this feature.
|
||||
#' @param selected The initially selected value (or multiple values if
|
||||
#' \code{multiple = TRUE}). If not specified then defaults to the first value
|
||||
#' for single-select lists and no values for multiple select lists.
|
||||
@@ -34,21 +39,38 @@
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#'
|
||||
#' ui <- fluidPage(
|
||||
#' selectInput("variable", "Variable:",
|
||||
#' c("Cylinders" = "cyl",
|
||||
#' "Transmission" = "am",
|
||||
#' "Gears" = "gear")),
|
||||
#' tableOutput("data")
|
||||
#' # basic example
|
||||
#' shinyApp(
|
||||
#' ui = fluidPage(
|
||||
#' selectInput("variable", "Variable:",
|
||||
#' c("Cylinders" = "cyl",
|
||||
#' "Transmission" = "am",
|
||||
#' "Gears" = "gear")),
|
||||
#' tableOutput("data")
|
||||
#' ),
|
||||
#' server = function(input, output) {
|
||||
#' output$data <- renderTable({
|
||||
#' mtcars[, c("mpg", input$variable), drop = FALSE]
|
||||
#' }, rownames = TRUE)
|
||||
#' }
|
||||
#' )
|
||||
#'
|
||||
#' server <- function(input, output) {
|
||||
#' output$data <- renderTable({
|
||||
#' mtcars[, c("mpg", input$variable), drop = FALSE]
|
||||
#' }, rownames = TRUE)
|
||||
#' }
|
||||
#'
|
||||
#' shinyApp(ui, server)
|
||||
#' # demoing optgroup support in the `choices` arg
|
||||
#' shinyApp(
|
||||
#' ui = fluidPage(
|
||||
#' selectInput("state", "Choose a state:",
|
||||
#' list(`East Coast` = c("NY", "NJ", "CT"),
|
||||
#' `West Coast` = c("WA", "OR", "CA"),
|
||||
#' `Midwest` = c("MN", "WI", "IA"))
|
||||
#' ),
|
||||
#' textOutput("result")
|
||||
#' ),
|
||||
#' server = function(input, output) {
|
||||
#' output$result <- renderText({
|
||||
#' paste("You chose", input$state)
|
||||
#' })
|
||||
#' }
|
||||
#' )
|
||||
#' }
|
||||
#' @export
|
||||
selectInput <- function(inputId, label, choices, selected = NULL,
|
||||
@@ -133,7 +155,7 @@ needOptgroup <- function(choices) {
|
||||
#' @rdname selectInput
|
||||
#' @param ... Arguments passed to \code{selectInput()}.
|
||||
#' @param options A list of options. See the documentation of \pkg{selectize.js}
|
||||
#' for possible options (character option values inside \code{\link{I}()} will
|
||||
#' for possible options (character option values inside \code{\link[base]{I}()} will
|
||||
#' be treated as literal JavaScript code; see \code{\link{renderDataTable}()}
|
||||
#' for details).
|
||||
#' @param width The width of the input, e.g. \code{'400px'}, or \code{'100\%'};
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
#' format string, to be passed to the Javascript strftime library. See
|
||||
#' \url{https://github.com/samsonjs/strftime} for more details. The allowed
|
||||
#' format specifications are very similar, but not identical, to those for R's
|
||||
#' \code{\link{strftime}} function. For Dates, the default is \code{"\%F"}
|
||||
#' \code{\link[base]{strftime}} function. For Dates, the default is \code{"\%F"}
|
||||
#' (like \code{"2015-07-01"}), and for POSIXt, the default is \code{"\%F \%T"}
|
||||
#' (like \code{"2015-07-01 15:32:10"}).
|
||||
#' @param timezone Only used if the values are POSIXt objects. A string
|
||||
@@ -51,6 +51,7 @@
|
||||
#' @examples
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' ui <- fluidPage(
|
||||
#' sliderInput("obs", "Number of observations:",
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
#' Create a submit button
|
||||
#'
|
||||
#' Create a submit button for an input form. Forms that include a submit
|
||||
#' Create a submit button for an app. Apps that include a submit
|
||||
#' button do not automatically update their outputs when inputs change,
|
||||
#' rather they wait until the user explicitly clicks the submit button.
|
||||
#' The use of \code{submitButton} is generally discouraged in favor of
|
||||
#' the more versatile \code{\link{actionButton}} (see details below).
|
||||
#'
|
||||
#' Submit buttons are unusual Shiny inputs, and we recommend using
|
||||
#' \code{\link{actionButton}} instead of \code{submitButton} when you
|
||||
#' want to delay a reaction.
|
||||
#' See \href{http://shiny.rstudio.com/articles/action-buttons.html}{this
|
||||
#' article} for more information (including a demo of how to "translate"
|
||||
#' code using a \code{submitButton} to code using an \code{actionButton}).
|
||||
#'
|
||||
#' In essence, the presence of a submit button stops all inputs from
|
||||
#' sending their values automatically to the server. This means, for
|
||||
#' instance, that if there are \emph{two} submit buttons in the same app,
|
||||
#' clicking either one will cause all inputs in the app to send their
|
||||
#' values to the server. This is probably not what you'd want, which is
|
||||
#' why submit button are unwieldy for all but the simplest apps. There
|
||||
#' are other problems with submit buttons: for example, dynamically
|
||||
#' created submit buttons (for example, with \code{\link{renderUI}}
|
||||
#' or \code{\link{insertUI}}) will not work.
|
||||
#'
|
||||
#' @param text Button caption
|
||||
#' @param icon Optional \code{\link{icon}} to appear on the button
|
||||
@@ -13,8 +32,26 @@
|
||||
#' @family input elements
|
||||
#'
|
||||
#' @examples
|
||||
#' submitButton("Update View")
|
||||
#' submitButton("Update View", icon("refresh"))
|
||||
#' if (interactive()) {
|
||||
#'
|
||||
#' shinyApp(
|
||||
#' ui = basicPage(
|
||||
#' numericInput("num", label = "Make changes", value = 1),
|
||||
#' submitButton("Update View", icon("refresh")),
|
||||
#' helpText("When you click the button above, you should see",
|
||||
#' "the output below update to reflect the value you",
|
||||
#' "entered at the top:"),
|
||||
#' verbatimTextOutput("value")
|
||||
#' ),
|
||||
#' server = function(input, output) {
|
||||
#'
|
||||
#' # submit buttons do not have a value of their own,
|
||||
#' # they control when the app accesses values of other widgets.
|
||||
#' # input$num is the value of the number widget.
|
||||
#' output$value <- renderPrint({ input$num })
|
||||
#' }
|
||||
#' )
|
||||
#' }
|
||||
#' @export
|
||||
submitButton <- function(text = "Apply Changes", icon = NULL, width = NULL) {
|
||||
div(
|
||||
|
||||
@@ -41,3 +41,229 @@ sessionHandler <- function(req) {
|
||||
shinysession$handleRequest(subreq)
|
||||
})
|
||||
}
|
||||
|
||||
apiHandler <- function(serverFuncSource) {
|
||||
function(req) {
|
||||
path <- req$PATH_INFO
|
||||
if (is.null(path))
|
||||
return(NULL)
|
||||
|
||||
matches <- regmatches(path, regexec('^/api/(.*)$', path))
|
||||
if (length(matches[[1]]) == 0)
|
||||
return(NULL)
|
||||
|
||||
apiName <- matches[[1]][2]
|
||||
|
||||
sharedSecret <- getOption('shiny.sharedSecret')
|
||||
if (!is.null(sharedSecret)
|
||||
&& !identical(sharedSecret, req$HTTP_SHINY_SHARED_SECRET)) {
|
||||
stop("Incorrect shared secret")
|
||||
}
|
||||
|
||||
if (!is.null(getOption("shiny.observer.error", NULL))) {
|
||||
warning(
|
||||
call. = FALSE,
|
||||
"options(shiny.observer.error) is no longer supported; please unset it!"
|
||||
)
|
||||
stopApp()
|
||||
}
|
||||
|
||||
# need to give a fake websocket to the session
|
||||
ws <- list(
|
||||
request = req,
|
||||
sendMessage = function(...) {
|
||||
#print(list(...))
|
||||
}
|
||||
)
|
||||
|
||||
# Accept JSON query string and/or JSON body as input values
|
||||
inputVals <- c(
|
||||
parseQueryStringJSON(req$QUERY_STRING),
|
||||
parseJSONBody(req)
|
||||
)
|
||||
|
||||
shinysession <- ShinySession$new(ws)
|
||||
on.exit({
|
||||
try({
|
||||
# Clean up the session. Very important, so that observers
|
||||
# and such don't hang around, and to let memory get gc'd.
|
||||
shinysession$wsClosed()
|
||||
appsByToken$remove(shinysession$token)
|
||||
})
|
||||
}, add = TRUE)
|
||||
appsByToken$set(shinysession$token, shinysession)
|
||||
shinysession$setShowcase(.globals$showcaseDefault)
|
||||
|
||||
serverFunc <- withReactiveDomain(NULL, serverFuncSource())
|
||||
|
||||
tryCatch({
|
||||
withReactiveDomain(shinysession, {
|
||||
shinysession$manageInputs(inputVals)
|
||||
do.call(serverFunc, argsForServerFunc(serverFunc, shinysession))
|
||||
result <- NULL
|
||||
shinysession$enableApi(apiName, function(value) {
|
||||
result <<- try(withLogErrors(value), silent = TRUE)
|
||||
})
|
||||
flushReact()
|
||||
resultToResponse(result)
|
||||
})
|
||||
}, error = function(e) {
|
||||
return(httpResponse(
|
||||
status=500,
|
||||
content=htmlEscape(conditionMessage(e))
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
apiWsHandler <- function(serverFuncSource) {
|
||||
function(ws) {
|
||||
path <- ws$request$PATH_INFO
|
||||
if (is.null(path))
|
||||
return(NULL)
|
||||
|
||||
matches <- regmatches(path, regexec('^/api/(.*)$', path))
|
||||
if (length(matches[[1]]) == 0)
|
||||
return(NULL)
|
||||
|
||||
apiName <- matches[[1]][2]
|
||||
|
||||
sharedSecret <- getOption('shiny.sharedSecret')
|
||||
if (!is.null(sharedSecret)
|
||||
&& !identical(sharedSecret, ws$request$HTTP_SHINY_SHARED_SECRET)) {
|
||||
ws$close()
|
||||
return(TRUE)
|
||||
}
|
||||
|
||||
if (!is.null(getOption("shiny.observer.error", NULL))) {
|
||||
warning(
|
||||
call. = FALSE,
|
||||
"options(shiny.observer.error) is no longer supported; please unset it!"
|
||||
)
|
||||
stopApp()
|
||||
}
|
||||
|
||||
inputVals <- parseQueryStringJSON(ws$request$QUERY_STRING)
|
||||
|
||||
# Give a fake websocket to suppress messages from session
|
||||
shinysession <- ShinySession$new(list(
|
||||
request = ws$request,
|
||||
sendMessage = function(...) {
|
||||
#print(list(...))
|
||||
}
|
||||
))
|
||||
appsByToken$set(shinysession$token, shinysession)
|
||||
shinysession$setShowcase(.globals$showcaseDefault)
|
||||
|
||||
serverFunc <- withReactiveDomain(NULL, serverFuncSource())
|
||||
|
||||
tryCatch({
|
||||
withReactiveDomain(shinysession, {
|
||||
shinysession$manageInputs(inputVals)
|
||||
do.call(serverFunc, argsForServerFunc(serverFunc, shinysession))
|
||||
shinysession$enableApi(apiName, function(value) {
|
||||
resp <- resultToResponse(value)
|
||||
if (resp$status != 200L) {
|
||||
warning("Error: ", responseToContent(resp))
|
||||
ws$close()
|
||||
} else {
|
||||
content <- responseToContent(resp)
|
||||
if (grepl("^image/", resp$content_type)) {
|
||||
content <- paste0("data:", resp$content_type, ";base64,",
|
||||
httpuv::rawToBase64(content))
|
||||
}
|
||||
try(ws$send(content), silent=TRUE)
|
||||
}
|
||||
})
|
||||
flushReact()
|
||||
})
|
||||
}, error = function(e) {
|
||||
ws$close()
|
||||
})
|
||||
|
||||
ws$onClose(function() {
|
||||
# Clean up the session. Very important, so that observers
|
||||
# and such don't hang around, and to let memory get gc'd.
|
||||
shinysession$wsClosed()
|
||||
appsByToken$remove(shinysession$token)
|
||||
})
|
||||
|
||||
# TODO: What to do on ws$onMessage?
|
||||
}
|
||||
}
|
||||
|
||||
parseJSONBody <- function(req) {
|
||||
if (identical(req[["REQUEST_METHOD"]], "POST")) {
|
||||
if (isTRUE(grepl(perl=TRUE, "^(text|application)/json(;\\s*charset\\s*=\\s*utf-8)?$", req[["HTTP_CONTENT_TYPE"]]))) {
|
||||
tmp <- file("", "w+b")
|
||||
on.exit(close(tmp))
|
||||
|
||||
input_file <- req[["rook.input"]]
|
||||
while (TRUE) {
|
||||
chunk <- input_file$read(8192L)
|
||||
if (length(chunk) == 0)
|
||||
break
|
||||
writeBin(chunk, tmp)
|
||||
}
|
||||
|
||||
return(jsonlite::fromJSON(tmp))
|
||||
}
|
||||
|
||||
if (is.null(req[["HTTP_CONTENT_TYPE"]])) {
|
||||
if (!is.null(req[["rook.input"]]) && length(req[["rook.input"]]$read(1L)) > 0) {
|
||||
stop("Invalid POST request (body provided without content type)")
|
||||
}
|
||||
return()
|
||||
}
|
||||
|
||||
stop("Invalid POST request (content type not supported)")
|
||||
}
|
||||
}
|
||||
|
||||
resultToResponse <- function(result) {
|
||||
if (inherits(result, "httpResponse")) {
|
||||
return(result)
|
||||
} else if (inherits(result, "try-error")) {
|
||||
return(httpResponse(
|
||||
status=500,
|
||||
content_type="text/plain",
|
||||
content=conditionMessage(attr(result, "condition"))
|
||||
))
|
||||
} else if (!is.null(attr(result, "content.type"))) {
|
||||
return(httpResponse(
|
||||
status=200L,
|
||||
content_type=attr(result, "content.type"),
|
||||
content=result
|
||||
))
|
||||
} else {
|
||||
return(httpResponse(
|
||||
status=200L,
|
||||
content_type="application/json",
|
||||
content=toJSON(result, pretty=TRUE)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
responseToContent <- function(result) {
|
||||
ct <- result$content_type
|
||||
textMode <- grepl("^text/", ct) || ct == "application/json" ||
|
||||
grepl("^application/xml($|\\+)", ct)
|
||||
|
||||
# TODO: Make sure text is UTF-8
|
||||
|
||||
if ("file" %in% names(result$content)) {
|
||||
filename <- result$content$file
|
||||
if ("owned" %in% names(result$content) && result$content$owned) {
|
||||
on.exit(unlink(filename), add = TRUE)
|
||||
}
|
||||
if (textMode)
|
||||
return(paste(readLines(filename), collapse = "\n"))
|
||||
else
|
||||
return(readBin(filename, raw(), file.info(filename)$size))
|
||||
} else {
|
||||
if (textMode)
|
||||
return(paste(result$content, collapse = "\n"))
|
||||
else
|
||||
return(result$content)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,6 +245,7 @@ Progress <- R6Class(
|
||||
#' @examples
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' ui <- fluidPage(
|
||||
#' plotOutput("plot")
|
||||
|
||||
414
R/reactives.R
414
R/reactives.R
@@ -344,7 +344,7 @@ as.list.reactivevalues <- function(x, all.names=FALSE, ...) {
|
||||
|
||||
#' Convert a reactivevalues object to a list
|
||||
#'
|
||||
#' This function does something similar to what you might \code{\link{as.list}}
|
||||
#' This function does something similar to what you might \code{\link[base]{as.list}}
|
||||
#' to do. The difference is that the calling context will take dependencies on
|
||||
#' every object in the reactivevalues object. To avoid taking dependencies on
|
||||
#' all the objects, you can wrap the call with \code{\link{isolate}()}.
|
||||
@@ -526,6 +526,7 @@ Observable <- R6Class(
|
||||
.mostRecentCtxId <<- ctx$id
|
||||
ctx$onInvalidate(function() {
|
||||
.invalidated <<- TRUE
|
||||
.value <<- NULL # Value can be GC'd, it won't be read once invalidated
|
||||
.dependents$invalidate()
|
||||
})
|
||||
.execCount <<- .execCount + 1L
|
||||
@@ -1109,7 +1110,7 @@ setAutoflush <- local({
|
||||
#' @return A no-parameter function that can be called from a reactive context,
|
||||
#' in order to cause that context to be invalidated the next time the timer
|
||||
#' interval elapses. Calling the returned function also happens to yield the
|
||||
#' current time (as in \code{\link{Sys.time}}).
|
||||
#' current time (as in \code{\link[base]{Sys.time}}).
|
||||
#' @seealso \code{\link{invalidateLater}}
|
||||
#'
|
||||
#' @examples
|
||||
@@ -1417,7 +1418,7 @@ reactiveFileReader <- function(intervalMillis, session, filePath, readFunc, ...)
|
||||
#' The expression given to \code{isolate()} is evaluated in the calling
|
||||
#' environment. This means that if you assign a variable inside the
|
||||
#' \code{isolate()}, its value will be visible outside of the \code{isolate()}.
|
||||
#' If you want to avoid this, you can use \code{\link{local}()} inside the
|
||||
#' If you want to avoid this, you can use \code{\link[base]{local}()} inside the
|
||||
#' \code{isolate()}.
|
||||
#'
|
||||
#' This function can also be useful for calling reactive expression at the
|
||||
@@ -1530,6 +1531,8 @@ maskReactiveContext <- function(expr) {
|
||||
#' invalidations that come from its reactive dependencies; it only invalidates
|
||||
#' in response to the given event.
|
||||
#'
|
||||
#' @section \code{ignoreNULL} and \code{ignoreInit}:
|
||||
#'
|
||||
#' Both \code{observeEvent} and \code{eventReactive} take an \code{ignoreNULL}
|
||||
#' parameter that affects behavior when the \code{eventExpr} evaluates to
|
||||
#' \code{NULL} (or in the special case of an \code{\link{actionButton}},
|
||||
@@ -1542,6 +1545,44 @@ maskReactiveContext <- function(expr) {
|
||||
#' the action/calculation and just let the user re-initiate it (like a
|
||||
#' "Recalculate" button).
|
||||
#'
|
||||
#' Unlike what happens for \code{ignoreNULL}, only \code{observeEvent} takes in an
|
||||
#' \code{ignoreInit} argument. By default, \code{observeEvent} will run right when
|
||||
#' it is created (except if, at that moment, \code{eventExpr} evaluates to \code{NULL}
|
||||
#' and \code{ignoreNULL} is \code{TRUE}). But when responding to a click of an action
|
||||
#' button, it may often be useful to set \code{ignoreInit} to \code{TRUE}. For
|
||||
#' example, if you're setting up an \code{observeEvent} for a dynamically created
|
||||
#' button, then \code{ignoreInit = TRUE} will guarantee that the action (in
|
||||
#' \code{handlerExpr}) will only be triggered when the button is actually clicked,
|
||||
#' instead of also being triggered when it is created/initialized.
|
||||
#'
|
||||
#' Even though \code{ignoreNULL} and \code{ignoreInit} can be used for similar
|
||||
#' purposes they are independent from one another. Here's the result of combining
|
||||
#' these:
|
||||
#'
|
||||
#' \describe{
|
||||
#' \item{\code{ignoreNULL = TRUE} and \code{ignoreInit = FALSE}}{
|
||||
#' This is the default. This combination means that \code{handlerExpr} will
|
||||
#' run every time that \code{eventExpr} is not \code{NULL}. If, at the time
|
||||
#' of the \code{observeEvent}'s creation, \code{handleExpr} happens to
|
||||
#' \emph{not} be \code{NULL}, then the code runs.
|
||||
#' }
|
||||
#' \item{\code{ignoreNULL = FALSE} and \code{ignoreInit = FALSE}}{
|
||||
#' This combination means that \code{handlerExpr} will run every time no
|
||||
#' matter what.
|
||||
#' }
|
||||
#' \item{\code{ignoreNULL = FALSE} and \code{ignoreInit = TRUE}}{
|
||||
#' This combination means that \code{handlerExpr} will \emph{not} run when
|
||||
#' the \code{observeEvent} is created (because \code{ignoreInit = TRUE}),
|
||||
#' but it will run every other time.
|
||||
#' }
|
||||
#' \item{\code{ignoreNULL = TRUE} and \code{ignoreInit = TRUE}}{
|
||||
#' This combination means that \code{handlerExpr} will \emph{not} run when
|
||||
#' the \code{observeEvent} is created (because \code{ignoreInit = TRUE}).
|
||||
#' After that, \code{handlerExpr} will run every time that \code{eventExpr}
|
||||
#' is not \code{NULL}.
|
||||
#' }
|
||||
#' }
|
||||
#'
|
||||
#' @param eventExpr A (quoted or unquoted) expression that represents the event;
|
||||
#' this can be a simple reactive value like \code{input$click}, a call to a
|
||||
#' reactive expression like \code{dataset()}, or even a complex expression
|
||||
@@ -1583,6 +1624,15 @@ maskReactiveContext <- function(expr) {
|
||||
#' @param ignoreNULL Whether the action should be triggered (or value
|
||||
#' calculated, in the case of \code{eventReactive}) when the input is
|
||||
#' \code{NULL}. See Details.
|
||||
#' @param ignoreInit If \code{TRUE}, then, when this \code{observeEvent} is
|
||||
#' first created/initialized, ignore the \code{handlerExpr} (the second
|
||||
#' argument), whether it is otherwise supposed to run or not. The default is
|
||||
#' \code{FALSE}. See Details.
|
||||
#' @param once Whether this \code{observeEvent} should be immediately destroyed
|
||||
#' after the first time that the code in \code{handlerExpr} is run. This
|
||||
#' pattern is useful when you want to subscribe to a event that should only
|
||||
#' happen once.
|
||||
#'
|
||||
#' @return \code{observeEvent} returns an observer reference class object (see
|
||||
#' \code{\link{observe}}). \code{eventReactive} returns a reactive expression
|
||||
#' object (see \code{\link{reactive}}).
|
||||
@@ -1592,37 +1642,71 @@ maskReactiveContext <- function(expr) {
|
||||
#' @examples
|
||||
#' ## Only run this example in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' ui <- fluidPage(
|
||||
#' column(4,
|
||||
#' numericInput("x", "Value", 5),
|
||||
#' br(),
|
||||
#' actionButton("button", "Show")
|
||||
#'
|
||||
#' ## App 1: Sample usage
|
||||
#' shinyApp(
|
||||
#' ui = fluidPage(
|
||||
#' column(4,
|
||||
#' numericInput("x", "Value", 5),
|
||||
#' br(),
|
||||
#' actionButton("button", "Show")
|
||||
#' ),
|
||||
#' column(8, tableOutput("table"))
|
||||
#' ),
|
||||
#' column(8, tableOutput("table"))
|
||||
#' server = function(input, output) {
|
||||
#' # Take an action every time button is pressed;
|
||||
#' # here, we just print a message to the console
|
||||
#' observeEvent(input$button, {
|
||||
#' cat("Showing", input$x, "rows\n")
|
||||
#' })
|
||||
#' # Take a reactive dependency on input$button, but
|
||||
#' # not on any of the stuff inside the function
|
||||
#' df <- eventReactive(input$button, {
|
||||
#' head(cars, input$x)
|
||||
#' })
|
||||
#' output$table <- renderTable({
|
||||
#' df()
|
||||
#' })
|
||||
#' }
|
||||
#' )
|
||||
#'
|
||||
#' ## App 2: Using `once`
|
||||
#' shinyApp(
|
||||
#' ui = basicPage( actionButton("go", "Go")),
|
||||
#' server = function(input, output, session) {
|
||||
#' observeEvent(input$go, {
|
||||
#' print(paste("This will only be printed once; all",
|
||||
#' "subsequent button clicks won't do anything"))
|
||||
#' }, once = TRUE)
|
||||
#' }
|
||||
#' )
|
||||
#'
|
||||
#' ## App 3: Using `ignoreInit` and `once`
|
||||
#' shinyApp(
|
||||
#' ui = basicPage(actionButton("go", "Go")),
|
||||
#' server = function(input, output, session) {
|
||||
#' observeEvent(input$go, {
|
||||
#' insertUI("#go", "afterEnd",
|
||||
#' actionButton("dynamic", "click to remove"))
|
||||
#'
|
||||
#' # set up an observer that depends on the dynamic
|
||||
#' # input, so that it doesn't run when the input is
|
||||
#' # created, and only runs once after that (since
|
||||
#' # the side effect is remove the input from the DOM)
|
||||
#' observeEvent(input$dynamic, {
|
||||
#' removeUI("#dynamic")
|
||||
#' }, ignoreInit = TRUE, once = TRUE)
|
||||
#' })
|
||||
#' }
|
||||
#' )
|
||||
#' server <- function(input, output) {
|
||||
#' # Take an action every time button is pressed;
|
||||
#' # here, we just print a message to the console
|
||||
#' observeEvent(input$button, {
|
||||
#' cat("Showing", input$x, "rows\n")
|
||||
#' })
|
||||
#' # Take a reactive dependency on input$button, but
|
||||
#' # not on any of the stuff inside the function
|
||||
#' df <- eventReactive(input$button, {
|
||||
#' head(cars, input$x)
|
||||
#' })
|
||||
#' output$table <- renderTable({
|
||||
#' df()
|
||||
#' })
|
||||
#' }
|
||||
#' shinyApp(ui=ui, server=server)
|
||||
#' }
|
||||
#' @export
|
||||
observeEvent <- function(eventExpr, handlerExpr,
|
||||
event.env = parent.frame(), event.quoted = FALSE,
|
||||
handler.env = parent.frame(), handler.quoted = FALSE,
|
||||
label=NULL, suspended=FALSE, priority=0, domain=getDefaultReactiveDomain(),
|
||||
autoDestroy = TRUE, ignoreNULL = TRUE) {
|
||||
label = NULL, suspended = FALSE, priority = 0,
|
||||
domain = getDefaultReactiveDomain(), autoDestroy = TRUE,
|
||||
ignoreNULL = TRUE, ignoreInit = FALSE, once = FALSE) {
|
||||
|
||||
eventFunc <- exprToFunction(eventExpr, event.env, event.quoted)
|
||||
if (is.null(label))
|
||||
@@ -1632,16 +1716,29 @@ observeEvent <- function(eventExpr, handlerExpr,
|
||||
handlerFunc <- exprToFunction(handlerExpr, handler.env, handler.quoted)
|
||||
handlerFunc <- wrapFunctionLabel(handlerFunc, "observeEventHandler", ..stacktraceon = TRUE)
|
||||
|
||||
invisible(observe({
|
||||
initialized <- FALSE
|
||||
|
||||
o <- observe({
|
||||
e <- eventFunc()
|
||||
|
||||
if (ignoreInit && !initialized) {
|
||||
initialized <<- TRUE
|
||||
return()
|
||||
}
|
||||
|
||||
if (ignoreNULL && isNullEvent(e)) {
|
||||
return()
|
||||
}
|
||||
|
||||
if (once) {
|
||||
on.exit(o$destroy())
|
||||
}
|
||||
|
||||
isolate(handlerFunc())
|
||||
}, label = label, suspended = suspended, priority = priority, domain = domain,
|
||||
autoDestroy = TRUE, ..stacktraceon = FALSE))
|
||||
autoDestroy = TRUE, ..stacktraceon = FALSE)
|
||||
|
||||
invisible(o)
|
||||
}
|
||||
|
||||
#' @rdname observeEvent
|
||||
@@ -1649,8 +1746,8 @@ observeEvent <- function(eventExpr, handlerExpr,
|
||||
eventReactive <- function(eventExpr, valueExpr,
|
||||
event.env = parent.frame(), event.quoted = FALSE,
|
||||
value.env = parent.frame(), value.quoted = FALSE,
|
||||
label=NULL, domain=getDefaultReactiveDomain(),
|
||||
ignoreNULL = TRUE) {
|
||||
label = NULL, domain = getDefaultReactiveDomain(),
|
||||
ignoreNULL = TRUE, ignoreInit = FALSE) {
|
||||
|
||||
eventFunc <- exprToFunction(eventExpr, event.env, event.quoted)
|
||||
if (is.null(label))
|
||||
@@ -1660,13 +1757,17 @@ eventReactive <- function(eventExpr, valueExpr,
|
||||
handlerFunc <- exprToFunction(valueExpr, value.env, value.quoted)
|
||||
handlerFunc <- wrapFunctionLabel(handlerFunc, "eventReactiveHandler", ..stacktraceon = TRUE)
|
||||
|
||||
initialized <- FALSE
|
||||
|
||||
invisible(reactive({
|
||||
e <- eventFunc()
|
||||
|
||||
validate(need(
|
||||
!ignoreNULL || !isNullEvent(e),
|
||||
message = FALSE
|
||||
))
|
||||
if (ignoreInit && !initialized) {
|
||||
initialized <<- TRUE
|
||||
req(FALSE)
|
||||
}
|
||||
|
||||
req(!ignoreNULL || !isNullEvent(e))
|
||||
|
||||
isolate(handlerFunc())
|
||||
}, label = label, domain = domain, ..stacktraceon = FALSE))
|
||||
@@ -1675,3 +1776,246 @@ eventReactive <- function(eventExpr, valueExpr,
|
||||
isNullEvent <- function(value) {
|
||||
is.null(value) || (inherits(value, 'shinyActionButtonValue') && value == 0)
|
||||
}
|
||||
|
||||
#' Slow down a reactive expression with debounce/throttle
|
||||
#'
|
||||
#' Transforms a reactive expression by preventing its invalidation signals from
|
||||
#' being sent unnecessarily often. This lets you ignore a very "chatty" reactive
|
||||
#' expression until it becomes idle, which is useful when the intermediate
|
||||
#' values don't matter as much as the final value, and the downstream
|
||||
#' calculations that depend on the reactive expression take a long time.
|
||||
#' \code{debounce} and \code{throttle} use different algorithms for slowing down
|
||||
#' invalidation signals; see Details.
|
||||
#'
|
||||
#' @section Limitations:
|
||||
#'
|
||||
#' Because R is single threaded, we can't come close to guaranteeing that the
|
||||
#' timing of debounce/throttle (or any other timing-related functions in
|
||||
#' Shiny) will be consistent or accurate; at the time we want to emit an
|
||||
#' invalidation signal, R may be performing a different task and we have no
|
||||
#' way to interrupt it (nor would we necessarily want to if we could).
|
||||
#' Therefore, it's best to think of the time windows you pass to these
|
||||
#' functions as minimums.
|
||||
#'
|
||||
#' You may also see undesirable behavior if the amount of time spent doing
|
||||
#' downstream processing for each change approaches or exceeds the time
|
||||
#' window: in this case, debounce/throttle may not have any effect, as the
|
||||
#' time each subsequent event is considered is already after the time window
|
||||
#' has expired.
|
||||
#'
|
||||
#' @details
|
||||
#'
|
||||
#' This is not a true debounce/throttle in that it will not prevent \code{r}
|
||||
#' from being called many times (in fact it may be called more times than
|
||||
#' usual), but rather, the reactive invalidation signal that is produced by
|
||||
#' \code{r} is debounced/throttled instead. Therefore, these functions should be
|
||||
#' used when \code{r} is cheap but the things it will trigger (downstream
|
||||
#' outputs and reactives) are expensive.
|
||||
#'
|
||||
#' Debouncing means that every invalidation from \code{r} will be held for the
|
||||
#' specified time window. If \code{r} invalidates again within that time window,
|
||||
#' then the timer starts over again. This means that as long as invalidations
|
||||
#' continually arrive from \code{r} within the time window, the debounced
|
||||
#' reactive will not invalidate at all. Only after the invalidations stop (or
|
||||
#' slow down sufficiently) will the downstream invalidation be sent.
|
||||
#'
|
||||
#' \code{ooo-oo-oo---- => -----------o-}
|
||||
#'
|
||||
#' (In this graphical depiction, each character represents a unit of time, and
|
||||
#' the time window is 3 characters.)
|
||||
#'
|
||||
#' Throttling, on the other hand, delays invalidation if the \emph{throttled}
|
||||
#' reactive recently (within the time window) invalidated. New \code{r}
|
||||
#' invalidations do not reset the time window. This means that if invalidations
|
||||
#' continually come from \code{r} within the time window, the throttled reactive
|
||||
#' will invalidate regularly, at a rate equal to or slower than than the time
|
||||
#' window.
|
||||
#'
|
||||
#' \code{ooo-oo-oo---- => o--o--o--o---}
|
||||
#'
|
||||
#' @param r A reactive expression (that invalidates too often).
|
||||
#' @param millis The debounce/throttle time window. You may optionally pass a
|
||||
#' no-arg function or reactive expression instead, e.g. to let the end-user
|
||||
#' control the time window.
|
||||
#' @param priority Debounce/throttle is implemented under the hood using
|
||||
#' \link[=observe]{observers}. Use this parameter to set the priority of
|
||||
#' these observers. Generally, this should be higher than the priorities of
|
||||
#' downstream observers and outputs (which default to zero).
|
||||
#' @param domain See \link{domains}.
|
||||
#'
|
||||
#' @examples
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' library(shiny)
|
||||
#' library(magrittr)
|
||||
#'
|
||||
#' ui <- fluidPage(
|
||||
#' plotOutput("plot", click = clickOpts("hover")),
|
||||
#' helpText("Quickly click on the plot above, while watching the result table below:"),
|
||||
#' tableOutput("result")
|
||||
#' )
|
||||
#'
|
||||
#' server <- function(input, output, session) {
|
||||
#' hover <- reactive({
|
||||
#' if (is.null(input$hover))
|
||||
#' list(x = NA, y = NA)
|
||||
#' else
|
||||
#' input$hover
|
||||
#' })
|
||||
#' hover_d <- hover %>% debounce(1000)
|
||||
#' hover_t <- hover %>% throttle(1000)
|
||||
#'
|
||||
#' output$plot <- renderPlot({
|
||||
#' plot(cars)
|
||||
#' })
|
||||
#'
|
||||
#' output$result <- renderTable({
|
||||
#' data.frame(
|
||||
#' mode = c("raw", "throttle", "debounce"),
|
||||
#' x = c(hover()$x, hover_t()$x, hover_d()$x),
|
||||
#' y = c(hover()$y, hover_t()$y, hover_d()$y)
|
||||
#' )
|
||||
#' })
|
||||
#' }
|
||||
#'
|
||||
#' shinyApp(ui, server)
|
||||
#' }
|
||||
#'
|
||||
#' @export
|
||||
debounce <- function(r, millis, priority = 100, domain = getDefaultReactiveDomain()) {
|
||||
|
||||
# TODO: make a nice label for the observer(s)
|
||||
|
||||
force(r)
|
||||
force(millis)
|
||||
|
||||
if (!is.function(millis)) {
|
||||
origMillis <- millis
|
||||
millis <- function() origMillis
|
||||
}
|
||||
|
||||
v <- reactiveValues(
|
||||
trigger = NULL,
|
||||
when = NULL # the deadline for the timer to fire; NULL if not scheduled
|
||||
)
|
||||
|
||||
# Responsible for tracking when f() changes.
|
||||
firstRun <- TRUE
|
||||
observe({
|
||||
r()
|
||||
|
||||
if (firstRun) {
|
||||
# During the first run we don't want to set v$when, as this will kick off
|
||||
# the timer. We only want to do that when we see r() change.
|
||||
firstRun <<- FALSE
|
||||
return()
|
||||
}
|
||||
|
||||
# The value (or possibly millis) changed. Start or reset the timer.
|
||||
v$when <- Sys.time() + millis()/1000
|
||||
}, label = "debounce tracker", domain = domain, priority = priority)
|
||||
|
||||
# This observer is the timer. It rests until v$when elapses, then touches
|
||||
# v$trigger.
|
||||
observe({
|
||||
if (is.null(v$when))
|
||||
return()
|
||||
|
||||
now <- Sys.time()
|
||||
if (now >= v$when) {
|
||||
# Mod by 999999999 to get predictable overflow behavior
|
||||
v$trigger <- isolate(v$trigger %OR% 0) %% 999999999 + 1
|
||||
v$when <- NULL
|
||||
} else {
|
||||
invalidateLater((v$when - now) * 1000)
|
||||
}
|
||||
}, label = "debounce timer", domain = domain, priority = priority)
|
||||
|
||||
# This is the actual reactive that is returned to the user. It returns the
|
||||
# value of r(), but only invalidates/updates when v$trigger is touched.
|
||||
er <- eventReactive(v$trigger, {
|
||||
r()
|
||||
}, label = "debounce result", ignoreNULL = FALSE, domain = domain)
|
||||
|
||||
# Force the value of er to be immediately cached upon creation. It's very hard
|
||||
# to explain why this observer is needed, but if you want to understand, try
|
||||
# commenting it out and studying the unit test failure that results.
|
||||
primer <- observe({
|
||||
primer$destroy()
|
||||
er()
|
||||
}, label = "debounce primer", domain = domain, priority = priority)
|
||||
|
||||
er
|
||||
}
|
||||
|
||||
#' @rdname debounce
|
||||
#' @export
|
||||
throttle <- function(r, millis, priority = 100, domain = getDefaultReactiveDomain()) {
|
||||
|
||||
# TODO: make a nice label for the observer(s)
|
||||
|
||||
force(r)
|
||||
force(millis)
|
||||
|
||||
if (!is.function(millis)) {
|
||||
origMillis <- millis
|
||||
millis <- function() origMillis
|
||||
}
|
||||
|
||||
v <- reactiveValues(
|
||||
trigger = 0,
|
||||
lastTriggeredAt = NULL, # Last time we fired; NULL if never
|
||||
pending = FALSE # If TRUE, trigger again when timer elapses
|
||||
)
|
||||
|
||||
blackoutMillisLeft <- function() {
|
||||
if (is.null(v$lastTriggeredAt)) {
|
||||
0
|
||||
} else {
|
||||
max(0, (v$lastTriggeredAt + millis()/1000) - Sys.time()) * 1000
|
||||
}
|
||||
}
|
||||
|
||||
trigger <- function() {
|
||||
v$lastTriggeredAt <- Sys.time()
|
||||
# Mod by 999999999 to get predictable overflow behavior
|
||||
v$trigger <- isolate(v$trigger) %% 999999999 + 1
|
||||
v$pending <- FALSE
|
||||
}
|
||||
|
||||
# Responsible for tracking when f() changes.
|
||||
observeEvent(r(), {
|
||||
if (v$pending) {
|
||||
# In a blackout period and someone already scheduled; do nothing
|
||||
} else if (blackoutMillisLeft() > 0) {
|
||||
# In a blackout period but this is the first change in that period; set
|
||||
# v$pending so that a trigger will be scheduled at the end of the period
|
||||
v$pending <- TRUE
|
||||
} else {
|
||||
# Not in a blackout period. Trigger, which will start a new blackout
|
||||
# period.
|
||||
trigger()
|
||||
}
|
||||
}, label = "throttle tracker", ignoreNULL = FALSE, priority = priority, domain = domain)
|
||||
|
||||
observe({
|
||||
if (!v$pending) {
|
||||
return()
|
||||
}
|
||||
|
||||
timeout <- blackoutMillisLeft()
|
||||
if (timeout > 0) {
|
||||
invalidateLater(timeout)
|
||||
} else {
|
||||
trigger()
|
||||
}
|
||||
}, priority = priority, domain = domain)
|
||||
|
||||
# This is the actual reactive that is returned to the user. It returns the
|
||||
# value of r(), but only invalidates/updates when v$trigger is touched.
|
||||
eventReactive(v$trigger, {
|
||||
r()
|
||||
}, label = "throttle result", ignoreNULL = FALSE, domain = domain)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
#' inline plot, you must provide numeric values (in pixels) to both
|
||||
#' \code{width} and \code{height}.
|
||||
#' @param res Resolution of resulting plot, in pixels per inch. This value is
|
||||
#' passed to \code{\link{png}}. Note that this affects the resolution of PNG
|
||||
#' passed to \code{\link[grDevices]{png}}. Note that this affects the resolution of PNG
|
||||
#' rendering in R; it won't change the actual ppi of the browser.
|
||||
#' @param ... Arguments to be passed through to \code{\link[grDevices]{png}}.
|
||||
#' These can be used to set the width, height, background color, etc.
|
||||
|
||||
89
R/server.R
89
R/server.R
@@ -34,7 +34,7 @@ registerClient <- function(client) {
|
||||
#' JavaScript/CSS files available to their components.
|
||||
#'
|
||||
#' @param prefix The URL prefix (without slashes). Valid characters are a-z,
|
||||
#' A-Z, 0-9, hyphen, period, and underscore; and must begin with a-z or A-Z.
|
||||
#' A-Z, 0-9, hyphen, period, and underscore.
|
||||
#' For example, a value of 'foo' means that any request paths that begin with
|
||||
#' '/foo' will be mapped to the given directory.
|
||||
#' @param directoryPath The directory that contains the static resources to be
|
||||
@@ -52,7 +52,7 @@ registerClient <- function(client) {
|
||||
#' @export
|
||||
addResourcePath <- function(prefix, directoryPath) {
|
||||
prefix <- prefix[1]
|
||||
if (!grepl('^[a-z][a-z0-9\\-_.]*$', prefix, ignore.case=TRUE, perl=TRUE)) {
|
||||
if (!grepl('^[a-z0-9\\-_][a-z0-9\\-_.]*$', prefix, ignore.case=TRUE, perl=TRUE)) {
|
||||
stop("addResourcePath called with invalid prefix; please see documentation")
|
||||
}
|
||||
|
||||
@@ -189,6 +189,7 @@ createAppHandlers <- function(httpHandlers, serverFuncSource) {
|
||||
appHandlers <- list(
|
||||
http = joinHandlers(c(
|
||||
sessionHandler,
|
||||
apiHandler(serverFuncSource),
|
||||
httpHandlers,
|
||||
sys.www.root,
|
||||
resourcePathHandler,
|
||||
@@ -200,6 +201,11 @@ createAppHandlers <- function(httpHandlers, serverFuncSource) {
|
||||
return(TRUE)
|
||||
}
|
||||
|
||||
if (grepl("^/api/", ws$request$PATH_INFO)) {
|
||||
apiWsHandler(serverFuncSource)(ws)
|
||||
return(TRUE)
|
||||
}
|
||||
|
||||
if (!is.null(getOption("shiny.observer.error", NULL))) {
|
||||
warning(
|
||||
call. = FALSE,
|
||||
@@ -462,6 +468,9 @@ serviceApp <- function() {
|
||||
|
||||
.shinyServerMinVersion <- '0.3.4'
|
||||
|
||||
# Global flag that's TRUE whenever we're inside of the scope of a call to runApp
|
||||
.globals$running <- FALSE
|
||||
|
||||
#' Run Shiny Application
|
||||
#'
|
||||
#' Runs a Shiny application. This function normally does not return; interrupt R
|
||||
@@ -503,6 +512,9 @@ serviceApp <- function() {
|
||||
#' application. If set to \code{"normal"}, displays the application normally.
|
||||
#' Defaults to \code{"auto"}, which displays the application in the mode given
|
||||
#' in its \code{DESCRIPTION} file, if any.
|
||||
#' @param test.mode Should the application be launched in test mode? This is
|
||||
#' only used for recording or running automated tests. Defaults to the
|
||||
#' \code{shiny.testmode} option, or FALSE if the option is not set.
|
||||
#'
|
||||
#' @examples
|
||||
#' \dontrun{
|
||||
@@ -515,6 +527,8 @@ serviceApp <- function() {
|
||||
#'
|
||||
#' ## Only run this example in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' # Apps can be run without a server.r and ui.r file
|
||||
#' runApp(list(
|
||||
#' ui = bootstrapPage(
|
||||
@@ -546,25 +560,73 @@ runApp <- function(appDir=getwd(),
|
||||
interactive()),
|
||||
host=getOption('shiny.host', '127.0.0.1'),
|
||||
workerId="", quiet=FALSE,
|
||||
display.mode=c("auto", "normal", "showcase")) {
|
||||
display.mode=c("auto", "normal", "showcase"),
|
||||
test.mode=getOption('shiny.testmode', FALSE)) {
|
||||
on.exit({
|
||||
handlerManager$clear()
|
||||
}, add = TRUE)
|
||||
|
||||
if (.globals$running) {
|
||||
stop("Can't call `runApp()` from within `runApp()`. If your ,",
|
||||
"application code contains `runApp()`, please remove it.")
|
||||
}
|
||||
.globals$running <- TRUE
|
||||
on.exit({
|
||||
.globals$running <- FALSE
|
||||
}, add = TRUE)
|
||||
|
||||
# Enable per-app Shiny options
|
||||
oldOptionSet <- .globals$options
|
||||
on.exit({
|
||||
.globals$options <- oldOptionSet
|
||||
},add = TRUE)
|
||||
|
||||
if (is.null(host) || is.na(host))
|
||||
host <- '0.0.0.0'
|
||||
|
||||
# Make warnings print immediately
|
||||
# Set pool.scheduler to support pool package
|
||||
ops <- options(warn = 1, pool.scheduler = scheduleTask)
|
||||
on.exit(options(ops), add = TRUE)
|
||||
|
||||
appParts <- as.shiny.appobj(appDir)
|
||||
|
||||
# The lines below set some of the app's running options, which
|
||||
# can be:
|
||||
# - left unspeficied (in which case the arguments' default
|
||||
# values from `runApp` kick in);
|
||||
# - passed through `shinyApp`
|
||||
# - passed through `runApp` (this function)
|
||||
# - passed through both `shinyApp` and `runApp` (the latter
|
||||
# takes precedence)
|
||||
#
|
||||
# Matrix of possibilities:
|
||||
# | IN shinyApp | IN runApp | result | check |
|
||||
# |-------------|-----------|--------------|----------------------------------------------------------------------------------------------------------------------------------------|
|
||||
# | no | no | use defaults | exhaust all possibilities: if it's missing (runApp does not specify); THEN if it's not in shinyApp appParts$options; THEN use defaults |
|
||||
# | yes | no | use shinyApp | if it's missing (runApp does not specify); THEN if it's in shinyApp appParts$options; THEN use shinyApp |
|
||||
# | no | yes | use runApp | if it's not missing (runApp specifies), use those |
|
||||
# | yes | yes | use runApp | if it's not missing (runApp specifies), use those |
|
||||
#
|
||||
# I tried to make this as compact and intuitive as possible,
|
||||
# given that there are four distinct possibilities to check
|
||||
appOps <- appParts$options
|
||||
findVal <- function(arg, default) {
|
||||
if (arg %in% names(appOps)) appOps[[arg]] else default
|
||||
}
|
||||
|
||||
if (missing(port))
|
||||
port <- findVal("port", port)
|
||||
if (missing(launch.browser))
|
||||
launch.browser <- findVal("launch.browser", launch.browser)
|
||||
if (missing(host))
|
||||
host <- findVal("host", host)
|
||||
if (missing(quiet))
|
||||
quiet <- findVal("quiet", quiet)
|
||||
if (missing(display.mode))
|
||||
display.mode <- findVal("display.mode", display.mode)
|
||||
if (missing(test.mode))
|
||||
test.mode <- findVal("test.mode", test.mode)
|
||||
|
||||
if (is.null(host) || is.na(host)) host <- '0.0.0.0'
|
||||
|
||||
workerId(workerId)
|
||||
|
||||
if (inShinyServer()) {
|
||||
@@ -584,6 +646,11 @@ runApp <- function(appDir=getwd(),
|
||||
# the display.mode parameter. The latter takes precedence.
|
||||
setShowcaseDefault(0)
|
||||
|
||||
.globals$testMode <- test.mode
|
||||
if (test.mode) {
|
||||
message("Running application in test mode.")
|
||||
}
|
||||
|
||||
# If appDir specifies a path, and display mode is specified in the
|
||||
# DESCRIPTION file at that path, apply it here.
|
||||
if (is.character(appDir)) {
|
||||
@@ -671,8 +738,6 @@ runApp <- function(appDir=getwd(),
|
||||
}
|
||||
}
|
||||
|
||||
appParts <- as.shiny.appobj(appDir)
|
||||
|
||||
# Extract appOptions (which is a list) and store them as shinyOptions, for
|
||||
# this app. (This is the only place we have to store settings that are
|
||||
# accessible both the UI and server portion of the app.)
|
||||
@@ -716,12 +781,16 @@ runApp <- function(appDir=getwd(),
|
||||
# Top-level ..stacktraceoff..; matches with ..stacktraceon in observe(),
|
||||
# reactive(), Callbacks$invoke(), and others
|
||||
..stacktraceoff..(
|
||||
captureStackTraces(
|
||||
captureStackTraces({
|
||||
# If any observers were created before runApp was called, this will make
|
||||
# sure they run once the app starts. (Issue #1013)
|
||||
scheduleFlush()
|
||||
|
||||
while (!.globals$stopped) {
|
||||
serviceApp()
|
||||
Sys.sleep(0.001)
|
||||
}
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
if (isTRUE(.globals$reterror)) {
|
||||
|
||||
182
R/shiny.R
182
R/shiny.R
@@ -276,6 +276,10 @@ workerId <- local({
|
||||
#' This is the request that was used to initiate the websocket connection
|
||||
#' (as opposed to the request that downloaded the web page for the app).
|
||||
#' }
|
||||
#' \item{userData}{
|
||||
#' An environment for app authors and module/package authors to store whatever
|
||||
#' session-specific data they want.
|
||||
#' }
|
||||
#' \item{resetBrush(brushId)}{
|
||||
#' Resets/clears the brush with the given \code{brushId}, if it exists on
|
||||
#' any \code{imageOutput} or \code{plotOutput} in the app.
|
||||
@@ -331,15 +335,15 @@ workerId <- local({
|
||||
#' }
|
||||
#' \item{exportTestValues()}{
|
||||
#' Registers expressions for export in test mode, available at the test
|
||||
#' endpoint URL.
|
||||
#' snapshot URL.
|
||||
#' }
|
||||
#' \item{getTestEndpointUrl(inputs=TRUE, outputs=TRUE, exports=TRUE,
|
||||
#' format="rds")}{
|
||||
#' Returns a URL for the test endpoint. Only has an effect when the
|
||||
#' \code{shiny.testmode} option is set to TRUE. For the inputs, outputs, and
|
||||
#' exports arguments, TRUE means to return all of these values. It is also
|
||||
#' \item{getTestSnapshotUrl(input=TRUE, output=TRUE, export=TRUE,
|
||||
#' format="json")}{
|
||||
#' Returns a URL for the test snapshots. Only has an effect when the
|
||||
#' \code{shiny.testmode} option is set to TRUE. For the input, output, and
|
||||
#' export arguments, TRUE means to return all of these values. It is also
|
||||
#' possible to specify by name which values to return by providing a
|
||||
#' character vector, as in \code{inputs=c("x", "y")}. The format can be
|
||||
#' character vector, as in \code{input=c("x", "y")}. The format can be
|
||||
#' "rds" or "json".
|
||||
#' }
|
||||
#'
|
||||
@@ -401,6 +405,7 @@ ShinySession <- R6Class(
|
||||
fileUploadContext = 'FileUploadContext',
|
||||
.input = 'ANY', # Internal ReactiveValues object for normal input sent from client
|
||||
.clientData = 'ANY', # Internal ReactiveValues object for other data sent from the client
|
||||
apiObservers = list(),
|
||||
busyCount = 0L, # Number of observer callbacks that are pending. When 0, we are idle
|
||||
closedCallbacks = 'Callbacks',
|
||||
flushCallbacks = 'Callbacks',
|
||||
@@ -412,9 +417,10 @@ ShinySession <- R6Class(
|
||||
restoredCallbacks = 'Callbacks',
|
||||
bookmarkExclude = character(0), # Names of inputs to exclude from bookmarking
|
||||
|
||||
testValueExprs = list(),
|
||||
testMode = FALSE, # Are we running in test mode?
|
||||
testExportExprs = list(),
|
||||
outputValues = list(), # Saved output values (for testing mode)
|
||||
testEndpointUrl = character(0),
|
||||
testSnapshotUrl = character(0),
|
||||
|
||||
sendResponse = function(requestMsg, value) {
|
||||
if (is.null(requestMsg$tag)) {
|
||||
@@ -579,71 +585,84 @@ ShinySession <- R6Class(
|
||||
private$outputValues <- mergeVectors(private$outputValues, values)
|
||||
},
|
||||
|
||||
enableTestEndpoint = function() {
|
||||
private$testEndpointUrl <- self$registerDataObj("shinytest", NULL,
|
||||
enableTestSnapshot = function() {
|
||||
private$testSnapshotUrl <- self$registerDataObj("shinytest", NULL,
|
||||
function(data, req) {
|
||||
if (!isTRUE(getOption("shiny.testmode"))) {
|
||||
if (!isTRUE(private$testMode)) {
|
||||
return()
|
||||
}
|
||||
|
||||
params <- parseQueryString(req$QUERY_STRING)
|
||||
# The format of the response that will be sent back. Default to "rds"
|
||||
# unless requested otherwise. The only other valid value is "json".
|
||||
format <- params$format %OR% "rds"
|
||||
# The format of the response that will be sent back. Defaults to
|
||||
# "json" unless requested otherwise. The only other valid value is
|
||||
# "rds".
|
||||
format <- params$format %OR% "json"
|
||||
|
||||
values <- list()
|
||||
|
||||
if (!is.null(params$inputs)) {
|
||||
if (!is.null(params$input)) {
|
||||
|
||||
allInputs <- isolate(
|
||||
reactiveValuesToList(self$input, all.names = TRUE)
|
||||
)
|
||||
|
||||
# If params$inputs is "1", return all; otherwise return just the
|
||||
# inputs that are named in params$inputs, like "x,y,z".
|
||||
if (params$inputs == "1") {
|
||||
values$inputs <- allInputs
|
||||
# If params$input is "1", return all; otherwise return just the
|
||||
# inputs that are named in params$input, like "x,y,z".
|
||||
if (params$input == "1") {
|
||||
values$input <- allInputs
|
||||
} else {
|
||||
items <- strsplit(params$inputs, ",")[[1]]
|
||||
items <- strsplit(params$input, ",")[[1]]
|
||||
items <- intersect(items, names(allInputs))
|
||||
values$inputs <- allInputs[items]
|
||||
values$input <- allInputs[items]
|
||||
}
|
||||
|
||||
values$input <- sortByName(values$input)
|
||||
}
|
||||
|
||||
if (!is.null(params$outputs)) {
|
||||
if (!is.null(params$output)) {
|
||||
|
||||
if (params$outputs == "1") {
|
||||
values$outputs <- private$outputValues
|
||||
if (params$output == "1") {
|
||||
values$output <- private$outputValues
|
||||
} else {
|
||||
items <- strsplit(params$outputs, ",")[[1]]
|
||||
items <- strsplit(params$output, ",")[[1]]
|
||||
items <- intersect(items, names(private$outputValues))
|
||||
values$outputs <- private$outputValues[items]
|
||||
values$output <- private$outputValues[items]
|
||||
}
|
||||
|
||||
values$output <- sortByName(values$output)
|
||||
}
|
||||
|
||||
if (!is.null(params$exports)) {
|
||||
if (!is.null(params$export)) {
|
||||
|
||||
testValueExprs <- private$testValueExprs
|
||||
if (params$exports == "1") {
|
||||
values$exports <- isolate(
|
||||
lapply(private$testValueExprs, function(item) {
|
||||
if (params$export == "1") {
|
||||
values$export <- isolate(
|
||||
lapply(private$testExportExprs, function(item) {
|
||||
eval(item$expr, envir = item$env)
|
||||
})
|
||||
)
|
||||
} else {
|
||||
items <- strsplit(params$exports, ",")[[1]]
|
||||
items <- intersect(items, names(private$testValueExprs))
|
||||
values$exports <- isolate(
|
||||
lapply(private$testValueExprs[items], function(item) {
|
||||
items <- strsplit(params$export, ",")[[1]]
|
||||
items <- intersect(items, names(private$testExportExprs))
|
||||
values$export <- isolate(
|
||||
lapply(private$testExportExprs[items], function(item) {
|
||||
eval(item$expr, envir = item$env)
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
values$export <- sortByName(values$export)
|
||||
}
|
||||
|
||||
# Make sure input, output, and export are all named lists (at this
|
||||
# point, they could be unnamed if they are empty lists). This is so
|
||||
# that the resulting object is represented as an object in JSON
|
||||
# instead of an array, and so that the RDS data structure is of a
|
||||
# consistent type.
|
||||
values <- lapply(values, asNamedVector)
|
||||
|
||||
if (length(values) == 0) {
|
||||
return(httpResponse(400, "text/plain",
|
||||
"No exports, inputs, or outputs requested."
|
||||
"None of export, input, or output requested."
|
||||
))
|
||||
}
|
||||
|
||||
@@ -671,6 +690,7 @@ ShinySession <- R6Class(
|
||||
progressStack = 'Stack', # Stack of progress objects
|
||||
input = 'reactivevalues', # Externally-usable S3 wrapper object for .input
|
||||
output = 'ANY', # Externally-usable S3 wrapper object for .outputs
|
||||
api = 'ANY', # Externally-usable S3 wrapper object for APIs
|
||||
clientData = 'reactivevalues', # Externally-usable S3 wrapper object for .clientData
|
||||
token = 'character', # Used to identify this instance in URLs
|
||||
files = 'Map', # For keeping track of files sent to client
|
||||
@@ -678,6 +698,7 @@ ShinySession <- R6Class(
|
||||
closed = logical(0),
|
||||
request = 'ANY', # Websocket request object
|
||||
singletons = character(0), # Tracks singleton HTML fragments sent to the page
|
||||
userData = 'environment',
|
||||
user = NULL,
|
||||
groups = NULL,
|
||||
|
||||
@@ -698,6 +719,7 @@ ShinySession <- R6Class(
|
||||
self$progressStack <- Stack$new()
|
||||
self$files <- Map$new()
|
||||
self$downloads <- Map$new()
|
||||
self$userData <- new.env(parent = emptyenv())
|
||||
|
||||
self$input <- .createReactiveValues(private$.input, readonly=TRUE)
|
||||
.setLabel(self$input, 'input')
|
||||
@@ -705,6 +727,7 @@ ShinySession <- R6Class(
|
||||
.setLabel(self$clientData, 'clientData')
|
||||
|
||||
self$output <- .createOutputWriter(self)
|
||||
self$api <- .createApiWriter(self)
|
||||
|
||||
self$token <- createUniqueId(16)
|
||||
private$.outputs <- list()
|
||||
@@ -716,7 +739,8 @@ ShinySession <- R6Class(
|
||||
private$restoredCallbacks <- Callbacks$new()
|
||||
private$createBookmarkObservers()
|
||||
|
||||
private$enableTestEndpoint()
|
||||
private$testMode <- .globals$testMode
|
||||
private$enableTestSnapshot()
|
||||
|
||||
private$registerSessionEndCallbacks()
|
||||
|
||||
@@ -1030,17 +1054,17 @@ ShinySession <- R6Class(
|
||||
shinyCallingHandlers(func()),
|
||||
shiny.custom.error = function(cond) {
|
||||
if (isTRUE(getOption("show.error.messages"))) printError(cond)
|
||||
structure(NULL, class = "try-error", condition = cond)
|
||||
structure(list(), class = "try-error", condition = cond)
|
||||
},
|
||||
shiny.output.cancel = function(cond) {
|
||||
structure(NULL, class = "cancel-output")
|
||||
structure(list(), class = "cancel-output")
|
||||
},
|
||||
shiny.silent.error = function(cond) {
|
||||
# Don't let shiny.silent.error go through the normal stop
|
||||
# path of try, because we don't want it to print. But we
|
||||
# do want to try to return the same looking result so that
|
||||
# the code below can send the error to the browser.
|
||||
structure(NULL, class = "try-error", condition = cond)
|
||||
structure(list(), class = "try-error", condition = cond)
|
||||
},
|
||||
error = function(cond) {
|
||||
if (isTRUE(getOption("show.error.messages"))) printError(cond)
|
||||
@@ -1049,7 +1073,7 @@ ShinySession <- R6Class(
|
||||
"logs or contact the app author for",
|
||||
"clarification."))
|
||||
}
|
||||
invisible(structure(NULL, class = "try-error", condition = cond))
|
||||
invisible(structure(list(), class = "try-error", condition = cond))
|
||||
},
|
||||
finally = {
|
||||
private$sendMessage(recalculating = list(
|
||||
@@ -1135,7 +1159,7 @@ ShinySession <- R6Class(
|
||||
inputMessages <- private$inputMessageQueue
|
||||
private$inputMessageQueue <- list()
|
||||
|
||||
if (isTRUE(getOption("shiny.testmode"))) {
|
||||
if (isTRUE(private$testMode)) {
|
||||
private$storeOutputValues(mergeVectors(values, errors))
|
||||
}
|
||||
|
||||
@@ -1331,11 +1355,11 @@ ShinySession <- R6Class(
|
||||
list(expr = expr, env = env_)
|
||||
})
|
||||
|
||||
private$testValueExprs <- mergeVectors(private$testValueExprs, items)
|
||||
private$testExportExprs <- mergeVectors(private$testExportExprs, items)
|
||||
},
|
||||
|
||||
getTestEndpointUrl = function(inputs = TRUE, outputs = TRUE, exports = TRUE,
|
||||
format = "rds") {
|
||||
getTestSnapshotUrl = function(input = TRUE, output = TRUE, export = TRUE,
|
||||
format = "json") {
|
||||
reqString <- function(group, value) {
|
||||
if (isTRUE(value))
|
||||
paste0(group, "=1")
|
||||
@@ -1345,10 +1369,10 @@ ShinySession <- R6Class(
|
||||
""
|
||||
}
|
||||
paste(
|
||||
private$testEndpointUrl,
|
||||
reqString("inputs", inputs),
|
||||
reqString("outputs", outputs),
|
||||
reqString("exports", exports),
|
||||
private$testSnapshotUrl,
|
||||
reqString("input", input),
|
||||
reqString("output", output),
|
||||
reqString("export", export),
|
||||
paste0("format=", format),
|
||||
sep = "&"
|
||||
)
|
||||
@@ -1611,6 +1635,19 @@ ShinySession <- R6Class(
|
||||
workerId(),
|
||||
URLencode(createUniqueId(8), TRUE)))
|
||||
},
|
||||
registerApi = function(name, func) {
|
||||
private$apiObservers[[name]] <- func
|
||||
},
|
||||
enableApi = function(name, callback) {
|
||||
rexpr <- private$apiObservers[[name]]
|
||||
if (is.null(rexpr)) {
|
||||
stop("API not found")
|
||||
}
|
||||
|
||||
observe({
|
||||
callback(..stacktraceon..(rexpr()))
|
||||
}, ..stacktraceon = FALSE)
|
||||
},
|
||||
# This function suspends observers for hidden outputs and resumes observers
|
||||
# for un-hidden outputs.
|
||||
manageHiddenOutputs = function() {
|
||||
@@ -1788,7 +1825,6 @@ outputOptions <- function(x, name, ...) {
|
||||
.subset2(x, 'impl')$outputOptions(name, ...)
|
||||
}
|
||||
|
||||
|
||||
#' Add callbacks for Shiny session events
|
||||
#'
|
||||
#' These functions are for registering callbacks on Shiny session events.
|
||||
@@ -1844,3 +1880,47 @@ flushAllSessions <- function() {
|
||||
NULL
|
||||
})
|
||||
}
|
||||
|
||||
.createApiWriter <- function(shinysession, ns = identity) {
|
||||
structure(list(impl=shinysession, ns=ns), class='shinyapi')
|
||||
}
|
||||
|
||||
#' @export
|
||||
`$<-.shinyapi` <- function(x, name, value) {
|
||||
name <- .subset2(x, 'ns')(name)
|
||||
|
||||
label <- deparse(substitute(value))
|
||||
if (length(substitute(value)) > 1) {
|
||||
# value is an object consisting of a call and its arguments. Here we want
|
||||
# to find the source references for the first argument (if there are
|
||||
# arguments), which generally corresponds to the reactive expression--
|
||||
# e.g. in renderTable({ x }), { x } is the expression to trace.
|
||||
attr(label, "srcref") <- srcrefFromShinyCall(substitute(value)[[2]])
|
||||
srcref <- attr(substitute(value)[[2]], "srcref")
|
||||
if (length(srcref) > 0)
|
||||
attr(label, "srcfile") <- srcFileOfRef(srcref[[1]])
|
||||
}
|
||||
.subset2(x, 'impl')$registerApi(name, value)
|
||||
return(invisible(x))
|
||||
}
|
||||
|
||||
#' @export
|
||||
`[[<-.shinyapi` <- `$<-.shinyapi`
|
||||
|
||||
#' @export
|
||||
`$.shinyapi` <- function(x, name) {
|
||||
stop("Reading objects from shinyapi object not allowed.")
|
||||
}
|
||||
|
||||
#' @export
|
||||
`[[.shinyapi` <- `$.shinyapi`
|
||||
|
||||
#' @export
|
||||
`[.shinyapi` <- function(values, name) {
|
||||
stop("Single-bracket indexing of shinyapi object is not allowed.")
|
||||
}
|
||||
|
||||
#' @export
|
||||
`[<-.shinyapi` <- function(values, name, value) {
|
||||
stop("Single-bracket indexing of shinyapi object is not allowed.")
|
||||
}
|
||||
|
||||
14
R/shinyui.R
14
R/shinyui.R
@@ -24,7 +24,7 @@ withMathJax <- function(...) {
|
||||
)
|
||||
}
|
||||
|
||||
renderPage <- function(ui, connection, showcase=0) {
|
||||
renderPage <- function(ui, connection, showcase=0, testMode=FALSE) {
|
||||
# If the ui is a NOT complete document (created by htmlTemplate()), then do some
|
||||
# preprocessing and make sure it's a complete document.
|
||||
if (!inherits(ui, "html_document")) {
|
||||
@@ -50,6 +50,14 @@ renderPage <- function(ui, connection, showcase=0) {
|
||||
script = if (getOption("shiny.minified", TRUE)) "shiny.min.js" else "shiny.js",
|
||||
stylesheet = "shiny.css")
|
||||
)
|
||||
|
||||
if (testMode) {
|
||||
# Add code injection listener if in test mode
|
||||
shiny_deps[[length(shiny_deps) + 1]] <-
|
||||
htmlDependency("shiny-testmode", utils::packageVersion("shiny"),
|
||||
c(href="shared"), script = "shiny-testmode.js")
|
||||
}
|
||||
|
||||
html <- renderDocument(ui, shiny_deps, processDep = createWebDependency)
|
||||
writeUTF8(html, con = connection)
|
||||
}
|
||||
@@ -91,6 +99,8 @@ uiHttpHandler <- function(ui, uiPattern = "^/$") {
|
||||
showcaseMode <- mode
|
||||
}
|
||||
|
||||
testMode <- .globals$testMode %OR% FALSE
|
||||
|
||||
# Create a restore context using query string
|
||||
bookmarkStore <- getShinyOption("bookmarkStore", default = "disable")
|
||||
if (bookmarkStore == "disable") {
|
||||
@@ -121,7 +131,7 @@ uiHttpHandler <- function(ui, uiPattern = "^/$") {
|
||||
if (is.null(uiValue))
|
||||
return(NULL)
|
||||
|
||||
renderPage(uiValue, textConn, showcaseMode)
|
||||
renderPage(uiValue, textConn, showcaseMode, testMode)
|
||||
html <- paste(readLines(textConn, encoding = 'UTF-8'), collapse='\n')
|
||||
return(httpResponse(200, content=enc2utf8(html)))
|
||||
}
|
||||
|
||||
@@ -127,6 +127,7 @@ as.tags.shiny.render.function <- function(x, ..., inline = FALSE) {
|
||||
#' @examples
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' ui <- fluidPage(
|
||||
#' sliderInput("n", "Number of observations", 2, 1000, 500),
|
||||
@@ -220,7 +221,7 @@ renderImage <- function(expr, env=parent.frame(), quoted=FALSE,
|
||||
#'
|
||||
#' Makes a reactive version of the given function that captures any printed
|
||||
#' output, and also captures its printable result (unless
|
||||
#' \code{\link{invisible}}), into a string. The resulting function is suitable
|
||||
#' \code{\link[base]{invisible}}), into a string. The resulting function is suitable
|
||||
#' for assigning to an \code{output} slot.
|
||||
#'
|
||||
#' The corresponding HTML output tag can be anything (though \code{pre} is
|
||||
@@ -232,14 +233,14 @@ renderImage <- function(expr, env=parent.frame(), quoted=FALSE,
|
||||
#'
|
||||
#' Note that unlike most other Shiny output functions, if the given function
|
||||
#' returns \code{NULL} then \code{NULL} will actually be visible in the output.
|
||||
#' To display nothing, make your function return \code{\link{invisible}()}.
|
||||
#' To display nothing, make your function return \code{\link[base]{invisible}()}.
|
||||
#'
|
||||
#' @param expr An expression that may print output and/or return a printable R
|
||||
#' object.
|
||||
#' @param env The environment in which to evaluate \code{expr}.
|
||||
#' @param quoted Is \code{expr} a quoted expression (with \code{quote()})? This
|
||||
#' is useful if you want to save an expression in a variable.
|
||||
#' @param width The value for \code{\link{options}('width')}.
|
||||
#' @param width The value for \code{\link[base]{options}('width')}.
|
||||
#' @param outputArgs A list of arguments to be passed through to the implicit
|
||||
#' call to \code{\link{verbatimTextOutput}} when \code{renderPrint} is used
|
||||
#' in an interactive R Markdown document.
|
||||
@@ -353,6 +354,98 @@ renderUI <- function(expr, env=parent.frame(), quoted=FALSE,
|
||||
markRenderFunction(uiOutput, renderFunc, outputArgs = outputArgs)
|
||||
}
|
||||
|
||||
#' @export
|
||||
serveJSON <- function(expr, env=parent.frame(), quoted=FALSE) {
|
||||
installExprFunction(expr, "func", env, quoted)
|
||||
function() {
|
||||
structure(
|
||||
toJSON(func(), pretty = TRUE),
|
||||
content.type = "application/json"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#' @export
|
||||
servePlot <- function(expr, env=parent.frame(), quoted=FALSE,
|
||||
defaultWidth = 600, defaultHeight = 400) {
|
||||
|
||||
if (!is.function(defaultWidth))
|
||||
defaultWidth <- valueToFunc(defaultWidth)
|
||||
if (!is.function(defaultHeight))
|
||||
defaultHeight <- valueToFunc(defaultHeight)
|
||||
|
||||
installExprFunction(expr, "func", env, quoted)
|
||||
function() {
|
||||
input <- getDefaultReactiveDomain()$input
|
||||
w <- if (!is.null(input$`plot-width`)) as.numeric(input$`plot-width`) else defaultWidth()
|
||||
h <- if (!is.null(input$`plot-height`)) as.numeric(input$`plot-height`) else defaultHeight()
|
||||
|
||||
pngfile <- plotPNG(function() {
|
||||
result <- withVisible(func())
|
||||
if (result$visible) {
|
||||
# Use capture.output to squelch printing to the actual console; we
|
||||
# are only interested in plot output
|
||||
utils::capture.output({
|
||||
# The value needs to be printed just in case it's an object that
|
||||
# requires printing to generate plot output, similar to ggplot2. But
|
||||
# for base graphics, it would already have been rendered when func was
|
||||
# called above, and the print should have no effect.
|
||||
print(result$value)
|
||||
})
|
||||
}
|
||||
}, width = w, height = h)
|
||||
|
||||
structure(
|
||||
list(file = pngfile, owned = TRUE),
|
||||
content.type = "image/png"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#' @importFrom utils write.csv
|
||||
#' @export
|
||||
serveCSV <- function(expr, env=parent.frame(), quoted=FALSE, row.names=FALSE) {
|
||||
installExprFunction(expr, "func", env, quoted)
|
||||
function() {
|
||||
tmp <- tempfile(".csv")
|
||||
write.csv(func(), tmp, row.names=row.names)
|
||||
structure(
|
||||
list(file = tmp, owned = TRUE),
|
||||
content.type = "text/csv"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#' @export
|
||||
serveText <- function(expr, env=parent.frame(), quoted=FALSE) {
|
||||
installExprFunction(expr, "func", env, quoted)
|
||||
function() {
|
||||
structure(
|
||||
paste(func(), collapse = "\n"),
|
||||
content.type = "text/plain"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#' @export
|
||||
serveRaw <- function(expr, env=parent.frame(), quoted=FALSE, contentType) {
|
||||
|
||||
if (!is.function(contentType))
|
||||
contentType <- valueToFunc(contentType)
|
||||
|
||||
installExprFunction(expr, "func", env, quoted)
|
||||
function() {
|
||||
bytes <- func()
|
||||
if (!is.raw(bytes)) {
|
||||
stop("serveRaw expects raw vector data")
|
||||
}
|
||||
structure(
|
||||
bytes,
|
||||
content.type = contentType()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#' File Downloads
|
||||
#'
|
||||
#' Allows content from the Shiny application to be made available to the user as
|
||||
@@ -420,7 +513,7 @@ downloadHandler <- function(filename, content, contentType=NA, outputArgs=list()
|
||||
#' the server infrastructure.
|
||||
#'
|
||||
#' For the \code{options} argument, the character elements that have the class
|
||||
#' \code{"AsIs"} (usually returned from \code{\link{I}()}) will be evaluated in
|
||||
#' \code{"AsIs"} (usually returned from \code{\link[base]{I}()}) will be evaluated in
|
||||
#' JavaScript. This is useful when the type of the option value is not supported
|
||||
#' in JSON, e.g., a JavaScript function, which can be obtained by evaluating a
|
||||
#' character string. Note this only applies to the root-level elements of the
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
#' Register expressions for export in test mode
|
||||
#'
|
||||
#' This function registers expressions that will be evaluated when a test export
|
||||
#' event occurs. These events are triggered by accessing an API endpoint URL.
|
||||
#' event occurs. These events are triggered by accessing a snapshot URL.
|
||||
#'
|
||||
#' This function only has an effect if the global option \code{shiny.testmode}
|
||||
#' is set to \code{TRUE}.
|
||||
#' This function only has an effect if the app is launched in test mode. This is
|
||||
#' done by calling \code{runApp()} with \code{test.mode=TRUE}, or by setting the
|
||||
#' global option \code{shiny.testmode} to \code{TRUE}.
|
||||
#'
|
||||
#' @param quoted_ Are the expression quoted? Default is \code{FALSE}.
|
||||
#' @param env_ The environment in which the expression should be evaluated.
|
||||
#' @param session_ A Shiny session object.
|
||||
#' @param ... Named arguments that are quoted or unquoted expressions that will
|
||||
#' be captured and evaluated when API endpoint is visited.
|
||||
#' be captured and evaluated when snapshot URL is visited.
|
||||
#' @examples
|
||||
#' ## Only run this example in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#'
|
||||
#' options(shiny.testmode = TRUE)
|
||||
#'
|
||||
#' # This application shows the test endpoint URL; clicking on it will
|
||||
#' # This application shows the test snapshot URL; clicking on it will
|
||||
#' # fetch the input, output, and exported values in JSON format.
|
||||
#' shinyApp(
|
||||
#' ui = basicPage(
|
||||
@@ -42,7 +43,7 @@
|
||||
#' )
|
||||
#'
|
||||
#' output$url <- renderUI({
|
||||
#' url <- session$getTestEndpointUrl(format="json")
|
||||
#' url <- session$getTestSnapshotUrl(format="json")
|
||||
#' a(href = url, url)
|
||||
#' })
|
||||
#'
|
||||
|
||||
47
R/utils.R
47
R/utils.R
@@ -182,6 +182,16 @@ anyUnnamed <- function(x) {
|
||||
any(!nzchar(nms))
|
||||
}
|
||||
|
||||
|
||||
# Given a vector/list, returns a named vector (the labels will be blank).
|
||||
asNamedVector <- function(x) {
|
||||
if (!is.null(names(x)))
|
||||
return(x)
|
||||
|
||||
names(x) <- rep.int("", length(x))
|
||||
x
|
||||
}
|
||||
|
||||
# Given two named vectors, join them together, and keep only the last element
|
||||
# with a given name in the resulting vector. If b has any elements with the same
|
||||
# name as elements in a, the element in a is dropped. Also, if there are any
|
||||
@@ -196,6 +206,20 @@ mergeVectors <- function(a, b) {
|
||||
x[!drop_idx]
|
||||
}
|
||||
|
||||
# Sort a vector by the names of items. If there are multiple items with the
|
||||
# same name, preserve the original order of those items. For empty
|
||||
# vectors/lists/NULL, return the original value.
|
||||
sortByName <- function(x) {
|
||||
if (anyUnnamed(x))
|
||||
stop("All items must be named")
|
||||
|
||||
# Special case for empty vectors/lists, and NULL
|
||||
if (length(x) == 0)
|
||||
return(x)
|
||||
|
||||
x[order(names(x))]
|
||||
}
|
||||
|
||||
# Wrapper around list2env with a NULL check. In R <3.2.0, if an empty unnamed
|
||||
# list is passed to list2env(), it errors. But an empty named list is OK. For
|
||||
# R >=3.2.0, this wrapper is not necessary.
|
||||
@@ -552,6 +576,20 @@ parseQueryString <- function(str, nested = FALSE) {
|
||||
res
|
||||
}
|
||||
|
||||
parseQueryStringJSON <- function(str, nested = FALSE) {
|
||||
vals <- parseQueryString(str, nested)
|
||||
mapply(names(vals), vals, SIMPLIFY = FALSE,
|
||||
FUN = function(name, value) {
|
||||
tryCatch(
|
||||
jsonlite::fromJSON(value),
|
||||
error = function(e) {
|
||||
stop("Failed to parse URL parameter \"", name, "\"")
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
# Assign value to the bottom element of the list x using recursive indices idx
|
||||
assignNestedList <- function(x = list(), idx, value) {
|
||||
for (i in seq_along(idx)) {
|
||||
@@ -1104,6 +1142,7 @@ reactiveStop <- function(message = "", class = NULL) {
|
||||
#' @examples
|
||||
#' ## Only run examples in interactive R sessions
|
||||
#' if (interactive()) {
|
||||
#' options(device.ask.default = FALSE)
|
||||
#'
|
||||
#' ui <- fluidPage(
|
||||
#' checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
|
||||
@@ -1206,7 +1245,7 @@ need <- function(expr, message = paste(label, "must be provided"), label) {
|
||||
#' \strong{Truthy and falsy values}
|
||||
#'
|
||||
#' The terms "truthy" and "falsy" generally indicate whether a value, when
|
||||
#' coerced to a \code{\link{logical}}, is \code{TRUE} or \code{FALSE}. We use
|
||||
#' coerced to a \code{\link[base]{logical}}, is \code{TRUE} or \code{FALSE}. We use
|
||||
#' the term a little loosely here; our usage tries to match the intuitive
|
||||
#' notions of "Is this value missing or available?", or "Has the user provided
|
||||
#' an answer?", or in the case of action buttons, "Has the button been
|
||||
@@ -1560,3 +1599,9 @@ Mutable <- R6Class("Mutable",
|
||||
get = function() { private$value }
|
||||
)
|
||||
)
|
||||
|
||||
# Turn a value into a no-arg function that returns that value
|
||||
valueToFunc <- function(val) {
|
||||
force(val)
|
||||
function() val
|
||||
}
|
||||
|
||||
@@ -59,6 +59,10 @@ devtools::install_version("shiny", version = "0.10.2.2")
|
||||
|
||||
The Javascript code in Shiny is minified using tools that run on Node.js. See the tools/ directory for more information.
|
||||
|
||||
## Guidelines for contributing
|
||||
|
||||
We welcome contributions to the **shiny** package. Please see our [CONTRIBUTING.md](CONTRIBUTING.md) file for detailed guidelines of how to contribute.
|
||||
|
||||
## License
|
||||
|
||||
The shiny package is licensed under the GPLv3. See these files in the inst directory for additional details:
|
||||
|
||||
@@ -1 +1 @@
|
||||
This example demonstrates some additional widgets included in Shiny, such as `helpText` and `submitButton`. The latter is used to delay rendering output until the user explicitly requests it.
|
||||
This example demonstrates some additional widgets included in Shiny, such as `helpText` and `actionButton`. The latter is used to delay rendering output until the user explicitly requests it (a construct which also introduces two important server functions, `eventReactive` and `isolate`).
|
||||
|
||||
@@ -1,26 +1,32 @@
|
||||
library(shiny)
|
||||
library(datasets)
|
||||
|
||||
# Define server logic required to summarize and view the
|
||||
# Define server logic required to summarize and view the
|
||||
# selected dataset
|
||||
function(input, output) {
|
||||
|
||||
# Return the requested dataset
|
||||
datasetInput <- reactive({
|
||||
|
||||
# Return the requested dataset. Note that we use `eventReactive()`
|
||||
# here, which takes a dependency on input$update (the action
|
||||
# button), so that the output is only updated when the user
|
||||
# clicks the button.
|
||||
datasetInput <- eventReactive(input$update, {
|
||||
switch(input$dataset,
|
||||
"rock" = rock,
|
||||
"pressure" = pressure,
|
||||
"cars" = cars)
|
||||
})
|
||||
|
||||
}, ignoreNULL = FALSE)
|
||||
|
||||
# Generate a summary of the dataset
|
||||
output$summary <- renderPrint({
|
||||
dataset <- datasetInput()
|
||||
summary(dataset)
|
||||
})
|
||||
|
||||
# Show the first "n" observations
|
||||
|
||||
# Show the first "n" observations. The use of `isolate()` here
|
||||
# is necessary because we don't want the table to update
|
||||
# whenever input$obs changes (only when the user clicks the
|
||||
# action button).
|
||||
output$view <- renderTable({
|
||||
head(datasetInput(), n = input$obs)
|
||||
head(datasetInput(), n = isolate(input$obs))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,32 +2,32 @@ library(shiny)
|
||||
|
||||
# Define UI for dataset viewer application
|
||||
fluidPage(
|
||||
|
||||
|
||||
# Application title.
|
||||
titlePanel("More Widgets"),
|
||||
|
||||
|
||||
# Sidebar with controls to select a dataset and specify the
|
||||
# number of observations to view. The helpText function is
|
||||
# also used to include clarifying text. Most notably, the
|
||||
# inclusion of a submitButton defers the rendering of output
|
||||
# inclusion of an actionButton defers the rendering of output
|
||||
# until the user explicitly clicks the button (rather than
|
||||
# doing it immediately when inputs change). This is useful if
|
||||
# the computations required to render output are inordinately
|
||||
# time-consuming.
|
||||
sidebarLayout(
|
||||
sidebarPanel(
|
||||
selectInput("dataset", "Choose a dataset:",
|
||||
selectInput("dataset", "Choose a dataset:",
|
||||
choices = c("rock", "pressure", "cars")),
|
||||
|
||||
|
||||
numericInput("obs", "Number of observations to view:", 10),
|
||||
|
||||
|
||||
helpText("Note: while the data view will show only the specified",
|
||||
"number of observations, the summary will still be based",
|
||||
"on the full dataset."),
|
||||
|
||||
submitButton("Update View")
|
||||
|
||||
actionButton("update", "Update View")
|
||||
),
|
||||
|
||||
|
||||
# Show a summary of the dataset and an HTML table with the
|
||||
# requested number of observations. Note the use of the h4
|
||||
# function to provide an additional header above each output
|
||||
@@ -35,7 +35,7 @@ fluidPage(
|
||||
mainPanel(
|
||||
h4("Summary"),
|
||||
verbatimTextOutput("summary"),
|
||||
|
||||
|
||||
h4("Observations"),
|
||||
tableOutput("view")
|
||||
)
|
||||
|
||||
@@ -115,24 +115,25 @@ sd_section("Rendering functions",
|
||||
"reactiveUI"
|
||||
)
|
||||
)
|
||||
sd_section("Reactive constructs",
|
||||
sd_section("Reactive programming",
|
||||
"A sub-library that provides reactive programming facilities for R.",
|
||||
c(
|
||||
"invalidateLater",
|
||||
"is.reactivevalues",
|
||||
"isolate",
|
||||
"makeReactiveBinding",
|
||||
"reactive",
|
||||
"observe",
|
||||
"observeEvent",
|
||||
"reactive",
|
||||
"reactiveValues",
|
||||
"reactiveValuesToList",
|
||||
"is.reactivevalues",
|
||||
"isolate",
|
||||
"invalidateLater",
|
||||
"debounce",
|
||||
"showReactLog",
|
||||
"makeReactiveBinding",
|
||||
"reactiveFileReader",
|
||||
"reactivePoll",
|
||||
"reactiveTimer",
|
||||
"reactiveValues",
|
||||
"reactiveValuesToList",
|
||||
"freezeReactiveValue",
|
||||
"domains",
|
||||
"showReactLog"
|
||||
"freezeReactiveValue"
|
||||
)
|
||||
)
|
||||
sd_section("Boilerplate",
|
||||
|
||||
144
inst/www/shared/font-awesome/css/font-awesome.css
vendored
144
inst/www/shared/font-awesome/css/font-awesome.css
vendored
@@ -1,13 +1,13 @@
|
||||
/*!
|
||||
* Font Awesome 4.6.3 by @davegandy - http://fontawesome.io - @fontawesome
|
||||
* Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome
|
||||
* License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
|
||||
*/
|
||||
/* FONT PATH
|
||||
* -------------------------- */
|
||||
@font-face {
|
||||
font-family: 'FontAwesome';
|
||||
src: url('../fonts/fontawesome-webfont.eot?v=4.6.3');
|
||||
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.6.3') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.6.3') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.6.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.6.3#fontawesomeregular') format('svg');
|
||||
src: url('../fonts/fontawesome-webfont.eot?v=4.7.0');
|
||||
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
@@ -1832,6 +1832,7 @@
|
||||
content: "\f23e";
|
||||
}
|
||||
.fa-battery-4:before,
|
||||
.fa-battery:before,
|
||||
.fa-battery-full:before {
|
||||
content: "\f240";
|
||||
}
|
||||
@@ -2178,6 +2179,143 @@
|
||||
.fa-font-awesome:before {
|
||||
content: "\f2b4";
|
||||
}
|
||||
.fa-handshake-o:before {
|
||||
content: "\f2b5";
|
||||
}
|
||||
.fa-envelope-open:before {
|
||||
content: "\f2b6";
|
||||
}
|
||||
.fa-envelope-open-o:before {
|
||||
content: "\f2b7";
|
||||
}
|
||||
.fa-linode:before {
|
||||
content: "\f2b8";
|
||||
}
|
||||
.fa-address-book:before {
|
||||
content: "\f2b9";
|
||||
}
|
||||
.fa-address-book-o:before {
|
||||
content: "\f2ba";
|
||||
}
|
||||
.fa-vcard:before,
|
||||
.fa-address-card:before {
|
||||
content: "\f2bb";
|
||||
}
|
||||
.fa-vcard-o:before,
|
||||
.fa-address-card-o:before {
|
||||
content: "\f2bc";
|
||||
}
|
||||
.fa-user-circle:before {
|
||||
content: "\f2bd";
|
||||
}
|
||||
.fa-user-circle-o:before {
|
||||
content: "\f2be";
|
||||
}
|
||||
.fa-user-o:before {
|
||||
content: "\f2c0";
|
||||
}
|
||||
.fa-id-badge:before {
|
||||
content: "\f2c1";
|
||||
}
|
||||
.fa-drivers-license:before,
|
||||
.fa-id-card:before {
|
||||
content: "\f2c2";
|
||||
}
|
||||
.fa-drivers-license-o:before,
|
||||
.fa-id-card-o:before {
|
||||
content: "\f2c3";
|
||||
}
|
||||
.fa-quora:before {
|
||||
content: "\f2c4";
|
||||
}
|
||||
.fa-free-code-camp:before {
|
||||
content: "\f2c5";
|
||||
}
|
||||
.fa-telegram:before {
|
||||
content: "\f2c6";
|
||||
}
|
||||
.fa-thermometer-4:before,
|
||||
.fa-thermometer:before,
|
||||
.fa-thermometer-full:before {
|
||||
content: "\f2c7";
|
||||
}
|
||||
.fa-thermometer-3:before,
|
||||
.fa-thermometer-three-quarters:before {
|
||||
content: "\f2c8";
|
||||
}
|
||||
.fa-thermometer-2:before,
|
||||
.fa-thermometer-half:before {
|
||||
content: "\f2c9";
|
||||
}
|
||||
.fa-thermometer-1:before,
|
||||
.fa-thermometer-quarter:before {
|
||||
content: "\f2ca";
|
||||
}
|
||||
.fa-thermometer-0:before,
|
||||
.fa-thermometer-empty:before {
|
||||
content: "\f2cb";
|
||||
}
|
||||
.fa-shower:before {
|
||||
content: "\f2cc";
|
||||
}
|
||||
.fa-bathtub:before,
|
||||
.fa-s15:before,
|
||||
.fa-bath:before {
|
||||
content: "\f2cd";
|
||||
}
|
||||
.fa-podcast:before {
|
||||
content: "\f2ce";
|
||||
}
|
||||
.fa-window-maximize:before {
|
||||
content: "\f2d0";
|
||||
}
|
||||
.fa-window-minimize:before {
|
||||
content: "\f2d1";
|
||||
}
|
||||
.fa-window-restore:before {
|
||||
content: "\f2d2";
|
||||
}
|
||||
.fa-times-rectangle:before,
|
||||
.fa-window-close:before {
|
||||
content: "\f2d3";
|
||||
}
|
||||
.fa-times-rectangle-o:before,
|
||||
.fa-window-close-o:before {
|
||||
content: "\f2d4";
|
||||
}
|
||||
.fa-bandcamp:before {
|
||||
content: "\f2d5";
|
||||
}
|
||||
.fa-grav:before {
|
||||
content: "\f2d6";
|
||||
}
|
||||
.fa-etsy:before {
|
||||
content: "\f2d7";
|
||||
}
|
||||
.fa-imdb:before {
|
||||
content: "\f2d8";
|
||||
}
|
||||
.fa-ravelry:before {
|
||||
content: "\f2d9";
|
||||
}
|
||||
.fa-eercast:before {
|
||||
content: "\f2da";
|
||||
}
|
||||
.fa-microchip:before {
|
||||
content: "\f2db";
|
||||
}
|
||||
.fa-snowflake-o:before {
|
||||
content: "\f2dc";
|
||||
}
|
||||
.fa-superpowers:before {
|
||||
content: "\f2dd";
|
||||
}
|
||||
.fa-wpexplorer:before {
|
||||
content: "\f2de";
|
||||
}
|
||||
.fa-meetup:before {
|
||||
content: "\f2e0";
|
||||
}
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
Before Width: | Height: | Size: 382 KiB After Width: | Height: | Size: 434 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
8
inst/www/shared/shiny-testmode.js
Normal file
8
inst/www/shared/shiny-testmode.js
Normal file
@@ -0,0 +1,8 @@
|
||||
// Listen for messages from parent frame. This file is only added when the
|
||||
// shiny.testmode option is TRUE.
|
||||
window.addEventListener("message", function(e) {
|
||||
var message = e.data;
|
||||
|
||||
if (message.code)
|
||||
eval(message.code);
|
||||
});
|
||||
@@ -1,3 +1,17 @@
|
||||
/* This is necessary so that an empty verbatimTextOutput slot
|
||||
is the same height as a non-empty one (only important when
|
||||
* placeholder = TRUE) */
|
||||
pre.shiny-text-output:empty::before {
|
||||
content: " ";
|
||||
}
|
||||
|
||||
pre.shiny-text-output.noplaceholder:empty {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border-width: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
#shiny-disconnected-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
|
||||
@@ -1160,7 +1160,8 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
// render the HTML and deps to a null target, so
|
||||
// the side-effect of rendering the deps, singletons,
|
||||
// and <head> still occur
|
||||
exports.renderHtml($([]), message.content.html, message.content.deps);
|
||||
console.warn('The selector you chose ("' + message.selector + '") could not be found in the DOM.');
|
||||
exports.renderHtml(message.content.html, $([]), message.content.deps);
|
||||
} else {
|
||||
targets.each(function (i, target) {
|
||||
exports.renderContent(target, message.content, message.where);
|
||||
@@ -1314,8 +1315,22 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
|
||||
// Returns a URL which can be queried to get values from inside the server
|
||||
// function. This is enabled with `options(shiny.testmode=TRUE)`.
|
||||
this.getTestEndpointUrl = function () {
|
||||
return "session/" + encodeURIComponent(this.config.sessionId) + "/dataobj/shinytest?w=" + encodeURIComponent(this.config.workerId) + "&nonce=" + randomId();
|
||||
this.getTestSnapshotBaseUrl = function () {
|
||||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
||||
|
||||
var _ref$fullUrl = _ref.fullUrl;
|
||||
var fullUrl = _ref$fullUrl === undefined ? true : _ref$fullUrl;
|
||||
|
||||
var loc = window.location;
|
||||
var url = "";
|
||||
|
||||
if (fullUrl) {
|
||||
// Strip off everything after last slash in path, like dirname() in R
|
||||
url = loc.origin + loc.pathname.replace(/\/[^/]*$/, "");
|
||||
}
|
||||
url += "/session/" + encodeURIComponent(this.config.sessionId) + "/dataobj/shinytest?w=" + encodeURIComponent(this.config.workerId) + "&nonce=" + randomId();
|
||||
|
||||
return url;
|
||||
};
|
||||
}).call(ShinyApp.prototype);
|
||||
|
||||
@@ -1373,22 +1388,22 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
var fadeDuration = 250;
|
||||
|
||||
function show() {
|
||||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
||||
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
||||
|
||||
var _ref$html = _ref.html;
|
||||
var html = _ref$html === undefined ? '' : _ref$html;
|
||||
var _ref$action = _ref.action;
|
||||
var action = _ref$action === undefined ? '' : _ref$action;
|
||||
var _ref$deps = _ref.deps;
|
||||
var deps = _ref$deps === undefined ? [] : _ref$deps;
|
||||
var _ref$duration = _ref.duration;
|
||||
var duration = _ref$duration === undefined ? 5000 : _ref$duration;
|
||||
var _ref$id = _ref.id;
|
||||
var id = _ref$id === undefined ? null : _ref$id;
|
||||
var _ref$closeButton = _ref.closeButton;
|
||||
var closeButton = _ref$closeButton === undefined ? true : _ref$closeButton;
|
||||
var _ref$type = _ref.type;
|
||||
var type = _ref$type === undefined ? null : _ref$type;
|
||||
var _ref2$html = _ref2.html;
|
||||
var html = _ref2$html === undefined ? '' : _ref2$html;
|
||||
var _ref2$action = _ref2.action;
|
||||
var action = _ref2$action === undefined ? '' : _ref2$action;
|
||||
var _ref2$deps = _ref2.deps;
|
||||
var deps = _ref2$deps === undefined ? [] : _ref2$deps;
|
||||
var _ref2$duration = _ref2.duration;
|
||||
var duration = _ref2$duration === undefined ? 5000 : _ref2$duration;
|
||||
var _ref2$id = _ref2.id;
|
||||
var id = _ref2$id === undefined ? null : _ref2$id;
|
||||
var _ref2$closeButton = _ref2.closeButton;
|
||||
var closeButton = _ref2$closeButton === undefined ? true : _ref2$closeButton;
|
||||
var _ref2$type = _ref2.type;
|
||||
var type = _ref2$type === undefined ? null : _ref2$type;
|
||||
|
||||
if (!id) id = randomId();
|
||||
|
||||
@@ -1532,12 +1547,12 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
// content is non-Bootstrap. Bootstrap modals require some special handling,
|
||||
// which is coded in here.
|
||||
show: function show() {
|
||||
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
||||
var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
||||
|
||||
var _ref2$html = _ref2.html;
|
||||
var html = _ref2$html === undefined ? '' : _ref2$html;
|
||||
var _ref2$deps = _ref2.deps;
|
||||
var deps = _ref2$deps === undefined ? [] : _ref2$deps;
|
||||
var _ref3$html = _ref3.html;
|
||||
var html = _ref3$html === undefined ? '' : _ref3$html;
|
||||
var _ref3$deps = _ref3.deps;
|
||||
var deps = _ref3$deps === undefined ? [] : _ref3$deps;
|
||||
|
||||
|
||||
// If there was an existing Bootstrap modal, then there will be a modal-
|
||||
@@ -1561,6 +1576,20 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
});
|
||||
}
|
||||
|
||||
$modal.on('keydown.shinymodal', function (e) {
|
||||
// If we're listening for Esc, don't let the event propagate. See
|
||||
// https://github.com/rstudio/shiny/issues/1453. The value of
|
||||
// data("keyboard") needs to be checked inside the handler, because at
|
||||
// the time that $modal.on() is called, the $("#shiny-modal") div doesn't
|
||||
// yet exist.
|
||||
if ($("#shiny-modal").data("keyboard") === false) return;
|
||||
|
||||
if (e.keyCode === 27) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// Set/replace contents of wrapper with html.
|
||||
exports.renderContent($modal, { html: html, deps: deps });
|
||||
},
|
||||
@@ -1568,6 +1597,8 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
remove: function remove() {
|
||||
var $modal = $('#shiny-modal-wrapper');
|
||||
|
||||
$modal.off('keydown.shinymodal');
|
||||
|
||||
// Look for a Bootstrap modal and if present, trigger hide event. This will
|
||||
// trigger the hidden.bs.modal callback that we set in show(), which unbinds
|
||||
// and removes the element.
|
||||
@@ -3091,6 +3122,10 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
exports.renderContent = function (el, content) {
|
||||
var where = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "replace";
|
||||
|
||||
if (where === "replace") {
|
||||
exports.unbindAll(el);
|
||||
}
|
||||
|
||||
exports.unbindAll(el);
|
||||
|
||||
var html;
|
||||
@@ -3148,8 +3183,10 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
var $head = $("head").first();
|
||||
|
||||
if (dep.meta) {
|
||||
var metas = $.map(asArray(dep.meta), function (content, name) {
|
||||
return $("<meta>").attr("name", name).attr("content", content);
|
||||
var metas = $.map(asArray(dep.meta), function (obj, idx) {
|
||||
// only one named pair is expected in obj as it's already been decomposed
|
||||
var name = Object.keys(obj)[0];
|
||||
return $("<meta>").attr("name", name).attr("content", obj[name]);
|
||||
});
|
||||
$head.append(metas);
|
||||
}
|
||||
@@ -4742,6 +4779,18 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
|
||||
self.onError(error);
|
||||
});
|
||||
this.$bar().text('Finishing upload');
|
||||
|
||||
// Trigger event when all files are finished uploading.
|
||||
var evt = jQuery.Event("shiny:fileuploaded");
|
||||
evt.name = this.id;
|
||||
evt.files = $.map(this.files, function (file, i) {
|
||||
return {
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
type: file.type
|
||||
};
|
||||
});
|
||||
$(document).trigger(evt);
|
||||
};
|
||||
this.onError = function (message) {
|
||||
this.$setError(message || '');
|
||||
|
||||
File diff suppressed because one or more lines are too long
8
inst/www/shared/shiny.min.js
vendored
8
inst/www/shared/shiny.min.js
vendored
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -8,7 +8,7 @@ addResourcePath(prefix, directoryPath)
|
||||
}
|
||||
\arguments{
|
||||
\item{prefix}{The URL prefix (without slashes). Valid characters are a-z,
|
||||
A-Z, 0-9, hyphen, period, and underscore; and must begin with a-z or A-Z.
|
||||
A-Z, 0-9, hyphen, period, and underscore.
|
||||
For example, a value of 'foo' means that any request paths that begin with
|
||||
'/foo' will be mapped to the given directory.}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ Dedicated functions are available for the most common HTML tags that do not
|
||||
conflict with common R functions.
|
||||
|
||||
The result from these functions is a tag object, which can be converted using
|
||||
\code{\link{as.character}()}.
|
||||
\code{\link[base]{as.character}()}.
|
||||
}
|
||||
\examples{
|
||||
doc <- tags$html(
|
||||
|
||||
@@ -56,7 +56,7 @@ the browser. It allows the following values:
|
||||
\item \code{yy} Year without century (12)
|
||||
\item \code{yyyy} Year with century (2012)
|
||||
\item \code{mm} Month number, with leading zero (01-12)
|
||||
\item \code{m} Month number, without leading zero (01-12)
|
||||
\item \code{m} Month number, without leading zero (1-12)
|
||||
\item \code{M} Abbreviated month name
|
||||
\item \code{MM} Full month name
|
||||
\item \code{dd} Day of month with leading zero
|
||||
|
||||
@@ -62,7 +62,7 @@ the browser. It allows the following values:
|
||||
\item \code{yy} Year without century (12)
|
||||
\item \code{yyyy} Year with century (2012)
|
||||
\item \code{mm} Month number, with leading zero (01-12)
|
||||
\item \code{m} Month number, without leading zero (01-12)
|
||||
\item \code{m} Month number, without leading zero (1-12)
|
||||
\item \code{M} Abbreviated month name
|
||||
\item \code{MM} Full month name
|
||||
\item \code{dd} Day of month with leading zero
|
||||
|
||||
122
man/debounce.Rd
Normal file
122
man/debounce.Rd
Normal file
@@ -0,0 +1,122 @@
|
||||
% Generated by roxygen2: do not edit by hand
|
||||
% Please edit documentation in R/reactives.R
|
||||
\name{debounce}
|
||||
\alias{debounce}
|
||||
\alias{throttle}
|
||||
\title{Slow down a reactive expression with debounce/throttle}
|
||||
\usage{
|
||||
debounce(r, millis, priority = 100, domain = getDefaultReactiveDomain())
|
||||
|
||||
throttle(r, millis, priority = 100, domain = getDefaultReactiveDomain())
|
||||
}
|
||||
\arguments{
|
||||
\item{r}{A reactive expression (that invalidates too often).}
|
||||
|
||||
\item{millis}{The debounce/throttle time window. You may optionally pass a
|
||||
no-arg function or reactive expression instead, e.g. to let the end-user
|
||||
control the time window.}
|
||||
|
||||
\item{priority}{Debounce/throttle is implemented under the hood using
|
||||
\link[=observe]{observers}. Use this parameter to set the priority of
|
||||
these observers. Generally, this should be higher than the priorities of
|
||||
downstream observers and outputs (which default to zero).}
|
||||
|
||||
\item{domain}{See \link{domains}.}
|
||||
}
|
||||
\description{
|
||||
Transforms a reactive expression by preventing its invalidation signals from
|
||||
being sent unnecessarily often. This lets you ignore a very "chatty" reactive
|
||||
expression until it becomes idle, which is useful when the intermediate
|
||||
values don't matter as much as the final value, and the downstream
|
||||
calculations that depend on the reactive expression take a long time.
|
||||
\code{debounce} and \code{throttle} use different algorithms for slowing down
|
||||
invalidation signals; see Details.
|
||||
}
|
||||
\details{
|
||||
This is not a true debounce/throttle in that it will not prevent \code{r}
|
||||
from being called many times (in fact it may be called more times than
|
||||
usual), but rather, the reactive invalidation signal that is produced by
|
||||
\code{r} is debounced/throttled instead. Therefore, these functions should be
|
||||
used when \code{r} is cheap but the things it will trigger (downstream
|
||||
outputs and reactives) are expensive.
|
||||
|
||||
Debouncing means that every invalidation from \code{r} will be held for the
|
||||
specified time window. If \code{r} invalidates again within that time window,
|
||||
then the timer starts over again. This means that as long as invalidations
|
||||
continually arrive from \code{r} within the time window, the debounced
|
||||
reactive will not invalidate at all. Only after the invalidations stop (or
|
||||
slow down sufficiently) will the downstream invalidation be sent.
|
||||
|
||||
\code{ooo-oo-oo---- => -----------o-}
|
||||
|
||||
(In this graphical depiction, each character represents a unit of time, and
|
||||
the time window is 3 characters.)
|
||||
|
||||
Throttling, on the other hand, delays invalidation if the \emph{throttled}
|
||||
reactive recently (within the time window) invalidated. New \code{r}
|
||||
invalidations do not reset the time window. This means that if invalidations
|
||||
continually come from \code{r} within the time window, the throttled reactive
|
||||
will invalidate regularly, at a rate equal to or slower than than the time
|
||||
window.
|
||||
|
||||
\code{ooo-oo-oo---- => o--o--o--o---}
|
||||
}
|
||||
\section{Limitations}{
|
||||
|
||||
|
||||
Because R is single threaded, we can't come close to guaranteeing that the
|
||||
timing of debounce/throttle (or any other timing-related functions in
|
||||
Shiny) will be consistent or accurate; at the time we want to emit an
|
||||
invalidation signal, R may be performing a different task and we have no
|
||||
way to interrupt it (nor would we necessarily want to if we could).
|
||||
Therefore, it's best to think of the time windows you pass to these
|
||||
functions as minimums.
|
||||
|
||||
You may also see undesirable behavior if the amount of time spent doing
|
||||
downstream processing for each change approaches or exceeds the time
|
||||
window: in this case, debounce/throttle may not have any effect, as the
|
||||
time each subsequent event is considered is already after the time window
|
||||
has expired.
|
||||
}
|
||||
\examples{
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
library(shiny)
|
||||
library(magrittr)
|
||||
|
||||
ui <- fluidPage(
|
||||
plotOutput("plot", click = clickOpts("hover")),
|
||||
helpText("Quickly click on the plot above, while watching the result table below:"),
|
||||
tableOutput("result")
|
||||
)
|
||||
|
||||
server <- function(input, output, session) {
|
||||
hover <- reactive({
|
||||
if (is.null(input$hover))
|
||||
list(x = NA, y = NA)
|
||||
else
|
||||
input$hover
|
||||
})
|
||||
hover_d <- hover \%>\% debounce(1000)
|
||||
hover_t <- hover \%>\% throttle(1000)
|
||||
|
||||
output$plot <- renderPlot({
|
||||
plot(cars)
|
||||
})
|
||||
|
||||
output$result <- renderTable({
|
||||
data.frame(
|
||||
mode = c("raw", "throttle", "debounce"),
|
||||
x = c(hover()$x, hover_t()$x, hover_d()$x),
|
||||
y = c(hover()$y, hover_t()$y, hover_d()$y)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
shinyApp(ui, server)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
\alias{downloadLink}
|
||||
\title{Create a download button or link}
|
||||
\usage{
|
||||
downloadButton(outputId, label = "Download", class = NULL)
|
||||
downloadButton(outputId, label = "Download", class = NULL, ...)
|
||||
|
||||
downloadLink(outputId, label = "Download", class = NULL)
|
||||
downloadLink(outputId, label = "Download", class = NULL, ...)
|
||||
}
|
||||
\arguments{
|
||||
\item{outputId}{The name of the output slot that the \code{downloadHandler}
|
||||
@@ -16,6 +16,8 @@ is assigned to.}
|
||||
\item{label}{The label that should appear on the button.}
|
||||
|
||||
\item{class}{Additional CSS classes to apply to the tag, if any.}
|
||||
|
||||
\item{...}{Other arguments to pass to the container tag function.}
|
||||
}
|
||||
\description{
|
||||
Use these functions to create a download button or link; when clicked, it
|
||||
|
||||
@@ -9,7 +9,7 @@ exportTestValues(..., quoted_ = FALSE, env_ = parent.frame(),
|
||||
}
|
||||
\arguments{
|
||||
\item{...}{Named arguments that are quoted or unquoted expressions that will
|
||||
be captured and evaluated when API endpoint is visited.}
|
||||
be captured and evaluated when snapshot URL is visited.}
|
||||
|
||||
\item{quoted_}{Are the expression quoted? Default is \code{FALSE}.}
|
||||
|
||||
@@ -19,11 +19,12 @@ be captured and evaluated when API endpoint is visited.}
|
||||
}
|
||||
\description{
|
||||
This function registers expressions that will be evaluated when a test export
|
||||
event occurs. These events are triggered by accessing an API endpoint URL.
|
||||
event occurs. These events are triggered by accessing a snapshot URL.
|
||||
}
|
||||
\details{
|
||||
This function only has an effect if the global option \code{shiny.testmode}
|
||||
is set to \code{TRUE}.
|
||||
This function only has an effect if the app is launched in test mode. This is
|
||||
done by calling \code{runApp()} with \code{test.mode=TRUE}, or by setting the
|
||||
global option \code{shiny.testmode} to \code{TRUE}.
|
||||
}
|
||||
\examples{
|
||||
## Only run this example in interactive R sessions
|
||||
@@ -31,7 +32,7 @@ if (interactive()) {
|
||||
|
||||
options(shiny.testmode = TRUE)
|
||||
|
||||
# This application shows the test endpoint URL; clicking on it will
|
||||
# This application shows the test snapshot URL; clicking on it will
|
||||
# fetch the input, output, and exported values in JSON format.
|
||||
shinyApp(
|
||||
ui = basicPage(
|
||||
@@ -56,7 +57,7 @@ shinyApp(
|
||||
)
|
||||
|
||||
output$url <- renderUI({
|
||||
url <- session$getTestEndpointUrl(format="json")
|
||||
url <- session$getTestSnapshotUrl(format="json")
|
||||
a(href = url, url)
|
||||
})
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ relationship.
|
||||
The expression given to \code{isolate()} is evaluated in the calling
|
||||
environment. This means that if you assign a variable inside the
|
||||
\code{isolate()}, its value will be visible outside of the \code{isolate()}.
|
||||
If you want to avoid this, you can use \code{\link{local}()} inside the
|
||||
If you want to avoid this, you can use \code{\link[base]{local}()} inside the
|
||||
\code{isolate()}.
|
||||
|
||||
This function can also be useful for calling reactive expression at the
|
||||
|
||||
@@ -9,11 +9,12 @@ observeEvent(eventExpr, handlerExpr, event.env = parent.frame(),
|
||||
event.quoted = FALSE, handler.env = parent.frame(),
|
||||
handler.quoted = FALSE, label = NULL, suspended = FALSE, priority = 0,
|
||||
domain = getDefaultReactiveDomain(), autoDestroy = TRUE,
|
||||
ignoreNULL = TRUE)
|
||||
ignoreNULL = TRUE, ignoreInit = FALSE, once = FALSE)
|
||||
|
||||
eventReactive(eventExpr, valueExpr, event.env = parent.frame(),
|
||||
event.quoted = FALSE, value.env = parent.frame(), value.quoted = FALSE,
|
||||
label = NULL, domain = getDefaultReactiveDomain(), ignoreNULL = TRUE)
|
||||
label = NULL, domain = getDefaultReactiveDomain(), ignoreNULL = TRUE,
|
||||
ignoreInit = FALSE)
|
||||
}
|
||||
\arguments{
|
||||
\item{eventExpr}{A (quoted or unquoted) expression that represents the event;
|
||||
@@ -61,6 +62,16 @@ automatically destroyed when its domain (if any) ends.}
|
||||
calculated, in the case of \code{eventReactive}) when the input is
|
||||
\code{NULL}. See Details.}
|
||||
|
||||
\item{ignoreInit}{If \code{TRUE}, then, when this \code{observeEvent} is
|
||||
first created/initialized, ignore the \code{handlerExpr} (the second
|
||||
argument), whether it is otherwise supposed to run or not. The default is
|
||||
\code{FALSE}. See Details.}
|
||||
|
||||
\item{once}{Whether this \code{observeEvent} should be immediately destroyed
|
||||
after the first time that the code in \code{handlerExpr} is run. This
|
||||
pattern is useful when you want to subscribe to a event that should only
|
||||
happen once.}
|
||||
|
||||
\item{valueExpr}{The expression that produces the return value of the
|
||||
\code{eventReactive}. It will be executed within an \code{\link{isolate}}
|
||||
scope.}
|
||||
@@ -108,6 +119,9 @@ updates in response to an event. This is just like a normal
|
||||
\link[=reactive]{reactive expression} except it ignores all the usual
|
||||
invalidations that come from its reactive dependencies; it only invalidates
|
||||
in response to the given event.
|
||||
}
|
||||
\section{\code{ignoreNULL} and \code{ignoreInit}}{
|
||||
|
||||
|
||||
Both \code{observeEvent} and \code{eventReactive} take an \code{ignoreNULL}
|
||||
parameter that affects behavior when the \code{eventExpr} evaluates to
|
||||
@@ -120,34 +134,105 @@ wait for the user to initiate the action first (like a "Submit" button);
|
||||
whereas \code{ignoreNULL=FALSE} is desirable if you want to initially perform
|
||||
the action/calculation and just let the user re-initiate it (like a
|
||||
"Recalculate" button).
|
||||
|
||||
Unlike what happens for \code{ignoreNULL}, only \code{observeEvent} takes in an
|
||||
\code{ignoreInit} argument. By default, \code{observeEvent} will run right when
|
||||
it is created (except if, at that moment, \code{eventExpr} evaluates to \code{NULL}
|
||||
and \code{ignoreNULL} is \code{TRUE}). But when responding to a click of an action
|
||||
button, it may often be useful to set \code{ignoreInit} to \code{TRUE}. For
|
||||
example, if you're setting up an \code{observeEvent} for a dynamically created
|
||||
button, then \code{ignoreInit = TRUE} will guarantee that the action (in
|
||||
\code{handlerExpr}) will only be triggered when the button is actually clicked,
|
||||
instead of also being triggered when it is created/initialized.
|
||||
|
||||
Even though \code{ignoreNULL} and \code{ignoreInit} can be used for similar
|
||||
purposes they are independent from one another. Here's the result of combining
|
||||
these:
|
||||
|
||||
\describe{
|
||||
\item{\code{ignoreNULL = TRUE} and \code{ignoreInit = FALSE}}{
|
||||
This is the default. This combination means that \code{handlerExpr} will
|
||||
run every time that \code{eventExpr} is not \code{NULL}. If, at the time
|
||||
of the \code{observeEvent}'s creation, \code{handleExpr} happens to
|
||||
\emph{not} be \code{NULL}, then the code runs.
|
||||
}
|
||||
\item{\code{ignoreNULL = FALSE} and \code{ignoreInit = FALSE}}{
|
||||
This combination means that \code{handlerExpr} will run every time no
|
||||
matter what.
|
||||
}
|
||||
\item{\code{ignoreNULL = FALSE} and \code{ignoreInit = TRUE}}{
|
||||
This combination means that \code{handlerExpr} will \emph{not} run when
|
||||
the \code{observeEvent} is created (because \code{ignoreInit = TRUE}),
|
||||
but it will run every other time.
|
||||
}
|
||||
\item{\code{ignoreNULL = TRUE} and \code{ignoreInit = TRUE}}{
|
||||
This combination means that \code{handlerExpr} will \emph{not} run when
|
||||
the \code{observeEvent} is created (because \code{ignoreInit = TRUE}).
|
||||
After that, \code{handlerExpr} will run every time that \code{eventExpr}
|
||||
is not \code{NULL}.
|
||||
}
|
||||
}
|
||||
}
|
||||
\examples{
|
||||
## Only run this example in interactive R sessions
|
||||
if (interactive()) {
|
||||
ui <- fluidPage(
|
||||
column(4,
|
||||
numericInput("x", "Value", 5),
|
||||
br(),
|
||||
actionButton("button", "Show")
|
||||
|
||||
## App 1: Sample usage
|
||||
shinyApp(
|
||||
ui = fluidPage(
|
||||
column(4,
|
||||
numericInput("x", "Value", 5),
|
||||
br(),
|
||||
actionButton("button", "Show")
|
||||
),
|
||||
column(8, tableOutput("table"))
|
||||
),
|
||||
column(8, tableOutput("table"))
|
||||
server = function(input, output) {
|
||||
# Take an action every time button is pressed;
|
||||
# here, we just print a message to the console
|
||||
observeEvent(input$button, {
|
||||
cat("Showing", input$x, "rows\\n")
|
||||
})
|
||||
# Take a reactive dependency on input$button, but
|
||||
# not on any of the stuff inside the function
|
||||
df <- eventReactive(input$button, {
|
||||
head(cars, input$x)
|
||||
})
|
||||
output$table <- renderTable({
|
||||
df()
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
## App 2: Using `once`
|
||||
shinyApp(
|
||||
ui = basicPage( actionButton("go", "Go")),
|
||||
server = function(input, output, session) {
|
||||
observeEvent(input$go, {
|
||||
print(paste("This will only be printed once; all",
|
||||
"subsequent button clicks won't do anything"))
|
||||
}, once = TRUE)
|
||||
}
|
||||
)
|
||||
|
||||
## App 3: Using `ignoreInit` and `once`
|
||||
shinyApp(
|
||||
ui = basicPage(actionButton("go", "Go")),
|
||||
server = function(input, output, session) {
|
||||
observeEvent(input$go, {
|
||||
insertUI("#go", "afterEnd",
|
||||
actionButton("dynamic", "click to remove"))
|
||||
|
||||
# set up an observer that depends on the dynamic
|
||||
# input, so that it doesn't run when the input is
|
||||
# created, and only runs once after that (since
|
||||
# the side effect is remove the input from the DOM)
|
||||
observeEvent(input$dynamic, {
|
||||
removeUI("#dynamic")
|
||||
}, ignoreInit = TRUE, once = TRUE)
|
||||
})
|
||||
}
|
||||
)
|
||||
server <- function(input, output) {
|
||||
# Take an action every time button is pressed;
|
||||
# here, we just print a message to the console
|
||||
observeEvent(input$button, {
|
||||
cat("Showing", input$x, "rows\\n")
|
||||
})
|
||||
# Take a reactive dependency on input$button, but
|
||||
# not on any of the stuff inside the function
|
||||
df <- eventReactive(input$button, {
|
||||
head(cars, input$x)
|
||||
})
|
||||
output$table <- renderTable({
|
||||
df()
|
||||
})
|
||||
}
|
||||
shinyApp(ui=ui, server=server)
|
||||
}
|
||||
}
|
||||
\seealso{
|
||||
|
||||
@@ -86,7 +86,7 @@ application page.
|
||||
}
|
||||
\note{
|
||||
The arguments \code{clickId} and \code{hoverId} only work for R base
|
||||
graphics (see the \pkg{\link{graphics}} package). They do not work for
|
||||
graphics (see the \pkg{\link[graphics:graphics-package]{graphics}} package). They do not work for
|
||||
\pkg{\link[grid:grid-package]{grid}}-based graphics, such as \pkg{ggplot2},
|
||||
\pkg{lattice}, and so on.
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ extension \code{.png}.}
|
||||
\item{height}{Height in pixels.}
|
||||
|
||||
\item{res}{Resolution in pixels per inch. This value is passed to
|
||||
\code{\link{png}}. Note that this affects the resolution of PNG rendering in
|
||||
\code{\link[grDevices]{png}}. Note that this affects the resolution of PNG rendering in
|
||||
R; it won't change the actual ppi of the browser.}
|
||||
|
||||
\item{...}{Arguments to be passed through to \code{\link[grDevices]{png}}.
|
||||
|
||||
@@ -18,7 +18,7 @@ occur.}
|
||||
A no-parameter function that can be called from a reactive context,
|
||||
in order to cause that context to be invalidated the next time the timer
|
||||
interval elapses. Calling the returned function also happens to yield the
|
||||
current time (as in \code{\link{Sys.time}}).
|
||||
current time (as in \code{\link[base]{Sys.time}}).
|
||||
}
|
||||
\description{
|
||||
Creates a reactive timer with the given interval. A reactive timer is like a
|
||||
|
||||
@@ -13,7 +13,7 @@ reactiveValuesToList(x, all.names = FALSE)
|
||||
\code{FALSE} (the default) don't include those objects.}
|
||||
}
|
||||
\description{
|
||||
This function does something similar to what you might \code{\link{as.list}}
|
||||
This function does something similar to what you might \code{\link[base]{as.list}}
|
||||
to do. The difference is that the calling context will take dependencies on
|
||||
every object in the reactivevalues object. To avoid taking dependencies on
|
||||
all the objects, you can wrap the call with \code{\link{isolate}()}.
|
||||
|
||||
@@ -45,7 +45,7 @@ the server infrastructure.
|
||||
}
|
||||
\details{
|
||||
For the \code{options} argument, the character elements that have the class
|
||||
\code{"AsIs"} (usually returned from \code{\link{I}()}) will be evaluated in
|
||||
\code{"AsIs"} (usually returned from \code{\link[base]{I}()}) will be evaluated in
|
||||
JavaScript. This is useful when the type of the option value is not supported
|
||||
in JSON, e.g., a JavaScript function, which can be obtained by evaluating a
|
||||
character string. Note this only applies to the root-level elements of the
|
||||
|
||||
@@ -47,6 +47,7 @@ the CSS class name \code{shiny-image-output}.
|
||||
\examples{
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
ui <- fluidPage(
|
||||
sliderInput("n", "Number of observations", 2, 1000, 500),
|
||||
|
||||
@@ -20,7 +20,7 @@ inline plot, you must provide numeric values (in pixels) to both
|
||||
\code{width} and \code{height}.}
|
||||
|
||||
\item{res}{Resolution of resulting plot, in pixels per inch. This value is
|
||||
passed to \code{\link{png}}. Note that this affects the resolution of PNG
|
||||
passed to \code{\link[grDevices]{png}}. Note that this affects the resolution of PNG
|
||||
rendering in R; it won't change the actual ppi of the browser.}
|
||||
|
||||
\item{...}{Arguments to be passed through to \code{\link[grDevices]{png}}.
|
||||
|
||||
@@ -16,7 +16,7 @@ object.}
|
||||
\item{quoted}{Is \code{expr} a quoted expression (with \code{quote()})? This
|
||||
is useful if you want to save an expression in a variable.}
|
||||
|
||||
\item{width}{The value for \code{\link{options}('width')}.}
|
||||
\item{width}{The value for \code{\link[base]{options}('width')}.}
|
||||
|
||||
\item{outputArgs}{A list of arguments to be passed through to the implicit
|
||||
call to \code{\link{verbatimTextOutput}} when \code{renderPrint} is used
|
||||
@@ -25,7 +25,7 @@ in an interactive R Markdown document.}
|
||||
\description{
|
||||
Makes a reactive version of the given function that captures any printed
|
||||
output, and also captures its printable result (unless
|
||||
\code{\link{invisible}}), into a string. The resulting function is suitable
|
||||
\code{\link[base]{invisible}}), into a string. The resulting function is suitable
|
||||
for assigning to an \code{output} slot.
|
||||
}
|
||||
\details{
|
||||
@@ -38,7 +38,7 @@ The result of executing \code{func} will be printed inside a
|
||||
|
||||
Note that unlike most other Shiny output functions, if the given function
|
||||
returns \code{NULL} then \code{NULL} will actually be visible in the output.
|
||||
To display nothing, make your function return \code{\link{invisible}()}.
|
||||
To display nothing, make your function return \code{\link[base]{invisible}()}.
|
||||
}
|
||||
\examples{
|
||||
isolate({
|
||||
|
||||
@@ -60,7 +60,7 @@ way to check for a value "inline" with its first use.
|
||||
\strong{Truthy and falsy values}
|
||||
|
||||
The terms "truthy" and "falsy" generally indicate whether a value, when
|
||||
coerced to a \code{\link{logical}}, is \code{TRUE} or \code{FALSE}. We use
|
||||
coerced to a \code{\link[base]{logical}}, is \code{TRUE} or \code{FALSE}. We use
|
||||
the term a little loosely here; our usage tries to match the intuitive
|
||||
notions of "Is this value missing or available?", or "Has the user provided
|
||||
an answer?", or in the case of action buttons, "Has the button been
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
runApp(appDir = getwd(), port = getOption("shiny.port"),
|
||||
launch.browser = getOption("shiny.launch.browser", interactive()),
|
||||
host = getOption("shiny.host", "127.0.0.1"), workerId = "",
|
||||
quiet = FALSE, display.mode = c("auto", "normal", "showcase"))
|
||||
quiet = FALSE, display.mode = c("auto", "normal", "showcase"),
|
||||
test.mode = getOption("shiny.testmode", FALSE))
|
||||
}
|
||||
\arguments{
|
||||
\item{appDir}{The application to run. Should be one of the following:
|
||||
@@ -46,6 +47,10 @@ the value \code{"showcase"}, shows application code and metadata from a
|
||||
application. If set to \code{"normal"}, displays the application normally.
|
||||
Defaults to \code{"auto"}, which displays the application in the mode given
|
||||
in its \code{DESCRIPTION} file, if any.}
|
||||
|
||||
\item{test.mode}{Should the application be launched in test mode? This is
|
||||
only used for recording or running automated tests. Defaults to the
|
||||
\code{shiny.testmode} option, or FALSE if the option is not set.}
|
||||
}
|
||||
\description{
|
||||
Runs a Shiny application. This function normally does not return; interrupt R
|
||||
@@ -69,6 +74,8 @@ runApp("myapp")
|
||||
|
||||
## Only run this example in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
# Apps can be run without a server.r and ui.r file
|
||||
runApp(list(
|
||||
ui = bootstrapPage(
|
||||
|
||||
@@ -16,7 +16,12 @@ selectizeInput(inputId, ..., options = NULL, width = NULL)
|
||||
\item{label}{Display label for the control, or \code{NULL} for no label.}
|
||||
|
||||
\item{choices}{List of values to select from. If elements of the list are
|
||||
named then that name rather than the value is displayed to the user.}
|
||||
named, then that name rather than the value is displayed to the user.
|
||||
This can also be a named list whose elements are (either named or
|
||||
unnamed) lists or vectors. If this is the case, the outermost names
|
||||
will be used as the "optgroup" label for the elements in the respective
|
||||
sublist. This allows you to group and label similar choices. See the
|
||||
example section for a small demo of this feature.}
|
||||
|
||||
\item{selected}{The initially selected value (or multiple values if
|
||||
\code{multiple = TRUE}). If not specified then defaults to the first value
|
||||
@@ -37,7 +42,7 @@ list, but when \code{size} is set, it will be a box instead.}
|
||||
\item{...}{Arguments passed to \code{selectInput()}.}
|
||||
|
||||
\item{options}{A list of options. See the documentation of \pkg{selectize.js}
|
||||
for possible options (character option values inside \code{\link{I}()} will
|
||||
for possible options (character option values inside \code{\link[base]{I}()} will
|
||||
be treated as literal JavaScript code; see \code{\link{renderDataTable}()}
|
||||
for details).}
|
||||
}
|
||||
@@ -73,21 +78,38 @@ The selectize input created from \code{selectizeInput()} allows
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
|
||||
ui <- fluidPage(
|
||||
selectInput("variable", "Variable:",
|
||||
c("Cylinders" = "cyl",
|
||||
"Transmission" = "am",
|
||||
"Gears" = "gear")),
|
||||
tableOutput("data")
|
||||
# basic example
|
||||
shinyApp(
|
||||
ui = fluidPage(
|
||||
selectInput("variable", "Variable:",
|
||||
c("Cylinders" = "cyl",
|
||||
"Transmission" = "am",
|
||||
"Gears" = "gear")),
|
||||
tableOutput("data")
|
||||
),
|
||||
server = function(input, output) {
|
||||
output$data <- renderTable({
|
||||
mtcars[, c("mpg", input$variable), drop = FALSE]
|
||||
}, rownames = TRUE)
|
||||
}
|
||||
)
|
||||
|
||||
server <- function(input, output) {
|
||||
output$data <- renderTable({
|
||||
mtcars[, c("mpg", input$variable), drop = FALSE]
|
||||
}, rownames = TRUE)
|
||||
}
|
||||
|
||||
shinyApp(ui, server)
|
||||
# demoing optgroup support in the `choices` arg
|
||||
shinyApp(
|
||||
ui = fluidPage(
|
||||
selectInput("state", "Choose a state:",
|
||||
list(`East Coast` = c("NY", "NJ", "CT"),
|
||||
`West Coast` = c("WA", "OR", "CA"),
|
||||
`Midwest` = c("MN", "WI", "IA"))
|
||||
),
|
||||
textOutput("result")
|
||||
),
|
||||
server = function(input, output) {
|
||||
output$result <- renderText({
|
||||
paste("You chose", input$state)
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
\seealso{
|
||||
|
||||
@@ -102,6 +102,10 @@
|
||||
This is the request that was used to initiate the websocket connection
|
||||
(as opposed to the request that downloaded the web page for the app).
|
||||
}
|
||||
\item{userData}{
|
||||
An environment for app authors and module/package authors to store whatever
|
||||
session-specific data they want.
|
||||
}
|
||||
\item{resetBrush(brushId)}{
|
||||
Resets/clears the brush with the given \code{brushId}, if it exists on
|
||||
any \code{imageOutput} or \code{plotOutput} in the app.
|
||||
@@ -157,15 +161,15 @@
|
||||
}
|
||||
\item{exportTestValues()}{
|
||||
Registers expressions for export in test mode, available at the test
|
||||
endpoint URL.
|
||||
snapshot URL.
|
||||
}
|
||||
\item{getTestEndpointUrl(inputs=TRUE, outputs=TRUE, exports=TRUE,
|
||||
format="rds")}{
|
||||
Returns a URL for the test endpoint. Only has an effect when the
|
||||
\code{shiny.testmode} option is set to TRUE. For the inputs, outputs, and
|
||||
exports arguments, TRUE means to return all of these values. It is also
|
||||
\item{getTestSnapshotUrl(input=TRUE, output=TRUE, export=TRUE,
|
||||
format="json")}{
|
||||
Returns a URL for the test snapshots. Only has an effect when the
|
||||
\code{shiny.testmode} option is set to TRUE. For the input, output, and
|
||||
export arguments, TRUE means to return all of these values. It is also
|
||||
possible to specify by name which values to return by providing a
|
||||
character vector, as in \code{inputs=c("x", "y")}. The format can be
|
||||
character vector, as in \code{input=c("x", "y")}. The format can be
|
||||
"rds" or "json".
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,9 +44,11 @@ is.shiny.appobj(x)
|
||||
This is only needed for \code{shinyAppObj}, since in the \code{shinyAppDir}
|
||||
case, a \code{global.R} file can be used for this purpose.}
|
||||
|
||||
\item{options}{Named options that should be passed to the `runApp` call. You
|
||||
can also specify \code{width} and \code{height} parameters which provide a
|
||||
hint to the embedding environment about the ideal height/width for the app.}
|
||||
\item{options}{Named options that should be passed to the \code{runApp} call
|
||||
(these can be any of the following: "port", "launch.browser", "host", "quiet",
|
||||
"display.mode" and "test.mode"). You can also specify \code{width} and
|
||||
\code{height} parameters which provide a hint to the embedding environment
|
||||
about the ideal height/width for the app.}
|
||||
|
||||
\item{uiPattern}{A regular expression that will be applied to each \code{GET}
|
||||
request to determine whether the \code{ui} should be used to handle the
|
||||
@@ -90,6 +92,8 @@ object to \code{print()} or \code{\link{runApp}()}.
|
||||
\examples{
|
||||
## Only run this example in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
shinyApp(
|
||||
ui = fluidPage(
|
||||
numericInput("n", "n", 1),
|
||||
|
||||
@@ -26,6 +26,7 @@ area occupies 2/3 of the horizontal width and typically contains outputs.
|
||||
\examples{
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
# Define UI
|
||||
ui <- fluidPage(
|
||||
|
||||
@@ -62,7 +62,7 @@ see \code{\link{validateCssUnit}}.}
|
||||
format string, to be passed to the Javascript strftime library. See
|
||||
\url{https://github.com/samsonjs/strftime} for more details. The allowed
|
||||
format specifications are very similar, but not identical, to those for R's
|
||||
\code{\link{strftime}} function. For Dates, the default is \code{"\%F"}
|
||||
\code{\link[base]{strftime}} function. For Dates, the default is \code{"\%F"}
|
||||
(like \code{"2015-07-01"}), and for POSIXt, the default is \code{"\%F \%T"}
|
||||
(like \code{"2015-07-01 15:32:10"}).}
|
||||
|
||||
@@ -95,6 +95,7 @@ Constructs a slider widget to select a numeric value from a range.
|
||||
\examples{
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
ui <- fluidPage(
|
||||
sliderInput("obs", "Number of observations:",
|
||||
|
||||
@@ -25,6 +25,7 @@ equal parts (by default).
|
||||
\examples{
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
# Server code used for all examples
|
||||
server <- function(input, output) {
|
||||
|
||||
@@ -18,13 +18,51 @@ see \code{\link{validateCssUnit}}.}
|
||||
A submit button that can be added to a UI definition.
|
||||
}
|
||||
\description{
|
||||
Create a submit button for an input form. Forms that include a submit
|
||||
Create a submit button for an app. Apps that include a submit
|
||||
button do not automatically update their outputs when inputs change,
|
||||
rather they wait until the user explicitly clicks the submit button.
|
||||
The use of \code{submitButton} is generally discouraged in favor of
|
||||
the more versatile \code{\link{actionButton}} (see details below).
|
||||
}
|
||||
\details{
|
||||
Submit buttons are unusual Shiny inputs, and we recommend using
|
||||
\code{\link{actionButton}} instead of \code{submitButton} when you
|
||||
want to delay a reaction.
|
||||
See \href{http://shiny.rstudio.com/articles/action-buttons.html}{this
|
||||
article} for more information (including a demo of how to "translate"
|
||||
code using a \code{submitButton} to code using an \code{actionButton}).
|
||||
|
||||
In essence, the presence of a submit button stops all inputs from
|
||||
sending their values automatically to the server. This means, for
|
||||
instance, that if there are \emph{two} submit buttons in the same app,
|
||||
clicking either one will cause all inputs in the app to send their
|
||||
values to the server. This is probably not what you'd want, which is
|
||||
why submit button are unwieldy for all but the simplest apps. There
|
||||
are other problems with submit buttons: for example, dynamically
|
||||
created submit buttons (for example, with \code{\link{renderUI}}
|
||||
or \code{\link{insertUI}}) will not work.
|
||||
}
|
||||
\examples{
|
||||
submitButton("Update View")
|
||||
submitButton("Update View", icon("refresh"))
|
||||
if (interactive()) {
|
||||
|
||||
shinyApp(
|
||||
ui = basicPage(
|
||||
numericInput("num", label = "Make changes", value = 1),
|
||||
submitButton("Update View", icon("refresh")),
|
||||
helpText("When you click the button above, you should see",
|
||||
"the output below update to reflect the value you",
|
||||
"entered at the top:"),
|
||||
verbatimTextOutput("value")
|
||||
),
|
||||
server = function(input, output) {
|
||||
|
||||
# submit buttons do not have a value of their own,
|
||||
# they control when the app accesses values of other widgets.
|
||||
# input$num is the value of the number widget.
|
||||
output$value <- renderPrint({ input$num })
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
\seealso{
|
||||
Other input.elements: \code{\link{actionButton}},
|
||||
|
||||
@@ -39,7 +39,7 @@ contain tags, text nodes, and HTML.}
|
||||
}
|
||||
\value{
|
||||
An HTML tag object that can be rendered as HTML using
|
||||
\code{\link{as.character}()}.
|
||||
\code{\link[base]{as.character}()}.
|
||||
}
|
||||
\description{
|
||||
\code{tag()} creates an HTML tag definition. Note that all of the valid HTML5
|
||||
|
||||
@@ -20,14 +20,19 @@ updateSelectizeInput(session, inputId, label = NULL, choices = NULL,
|
||||
\item{label}{The label to set for the input object.}
|
||||
|
||||
\item{choices}{List of values to select from. If elements of the list are
|
||||
named then that name rather than the value is displayed to the user.}
|
||||
named, then that name rather than the value is displayed to the user.
|
||||
This can also be a named list whose elements are (either named or
|
||||
unnamed) lists or vectors. If this is the case, the outermost names
|
||||
will be used as the "optgroup" label for the elements in the respective
|
||||
sublist. This allows you to group and label similar choices. See the
|
||||
example section for a small demo of this feature.}
|
||||
|
||||
\item{selected}{The initially selected value (or multiple values if
|
||||
\code{multiple = TRUE}). If not specified then defaults to the first value
|
||||
for single-select lists and no values for multiple select lists.}
|
||||
|
||||
\item{options}{A list of options. See the documentation of \pkg{selectize.js}
|
||||
for possible options (character option values inside \code{\link{I}()} will
|
||||
for possible options (character option values inside \code{\link[base]{I}()} will
|
||||
be treated as literal JavaScript code; see \code{\link{renderDataTable}()}
|
||||
for details).}
|
||||
|
||||
|
||||
@@ -80,6 +80,7 @@ as \code{a} does validate it.
|
||||
\examples{
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
ui <- fluidPage(
|
||||
checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
|
||||
|
||||
@@ -4,10 +4,14 @@
|
||||
\alias{verbatimTextOutput}
|
||||
\title{Create a verbatim text output element}
|
||||
\usage{
|
||||
verbatimTextOutput(outputId)
|
||||
verbatimTextOutput(outputId, placeholder = FALSE)
|
||||
}
|
||||
\arguments{
|
||||
\item{outputId}{output variable to read the value from}
|
||||
|
||||
\item{placeholder}{if the output is empty or \code{NULL}, should an empty
|
||||
rectangle be displayed to serve as a placeholder? (does not affect
|
||||
behavior when the the output in nonempty)}
|
||||
}
|
||||
\value{
|
||||
A verbatim text output element that can be included in a panel
|
||||
@@ -18,16 +22,23 @@ application page. The text will be included within an HTML \code{pre} tag.
|
||||
}
|
||||
\details{
|
||||
Text is HTML-escaped prior to rendering. This element is often used
|
||||
with the \link{renderPrint} function to preserve fixed-width formatting
|
||||
of printed objects.
|
||||
with the \link{renderPrint} function to preserve fixed-width formatting
|
||||
of printed objects.
|
||||
}
|
||||
\examples{
|
||||
mainPanel(
|
||||
h4("Summary"),
|
||||
verbatimTextOutput("summary"),
|
||||
|
||||
h4("Observations"),
|
||||
tableOutput("view")
|
||||
)
|
||||
## Only run this example in interactive R sessions
|
||||
if (interactive()) {
|
||||
shinyApp(
|
||||
ui = basicPage(
|
||||
textInput("txt", "Enter the text to display below:"),
|
||||
verbatimTextOutput("default"),
|
||||
verbatimTextOutput("placeholder", placeholder = TRUE)
|
||||
),
|
||||
server = function(input, output) {
|
||||
output$default <- renderText({ input$txt })
|
||||
output$placeholder <- renderText({ input$txt })
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ function.
|
||||
\examples{
|
||||
## Only run examples in interactive R sessions
|
||||
if (interactive()) {
|
||||
options(device.ask.default = FALSE)
|
||||
|
||||
ui <- fluidPage(
|
||||
plotOutput("plot")
|
||||
|
||||
@@ -126,6 +126,18 @@ $.extend(FileUploader.prototype, FileProcessor.prototype);
|
||||
self.onError(error);
|
||||
});
|
||||
this.$bar().text('Finishing upload');
|
||||
|
||||
// Trigger event when all files are finished uploading.
|
||||
var evt = jQuery.Event("shiny:fileuploaded");
|
||||
evt.name = this.id;
|
||||
evt.files = $.map(this.files, function(file, i) {
|
||||
return {
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
type: file.type
|
||||
};
|
||||
});
|
||||
$(document).trigger(evt);
|
||||
};
|
||||
this.onError = function(message) {
|
||||
this.$setError(message || '');
|
||||
|
||||
@@ -27,6 +27,21 @@ exports.modal = {
|
||||
});
|
||||
}
|
||||
|
||||
$modal.on('keydown.shinymodal', function(e) {
|
||||
// If we're listening for Esc, don't let the event propagate. See
|
||||
// https://github.com/rstudio/shiny/issues/1453. The value of
|
||||
// data("keyboard") needs to be checked inside the handler, because at
|
||||
// the time that $modal.on() is called, the $("#shiny-modal") div doesn't
|
||||
// yet exist.
|
||||
if ($("#shiny-modal").data("keyboard") === false)
|
||||
return;
|
||||
|
||||
if (e.keyCode === 27) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// Set/replace contents of wrapper with html.
|
||||
exports.renderContent($modal, { html: html, deps: deps });
|
||||
},
|
||||
@@ -34,6 +49,8 @@ exports.modal = {
|
||||
remove: function() {
|
||||
const $modal = $('#shiny-modal-wrapper');
|
||||
|
||||
$modal.off('keydown.shinymodal');
|
||||
|
||||
// Look for a Bootstrap modal and if present, trigger hide event. This will
|
||||
// trigger the hidden.bs.modal callback that we set in show(), which unbinds
|
||||
// and removes the element.
|
||||
|
||||
@@ -25,6 +25,10 @@ var renderDependencies = exports.renderDependencies = function(dependencies) {
|
||||
// inputs/outputs. `content` can be null, a string, or an object with
|
||||
// properties 'html' and 'deps'.
|
||||
exports.renderContent = function(el, content, where="replace") {
|
||||
if (where === "replace") {
|
||||
exports.unbindAll(el);
|
||||
}
|
||||
|
||||
exports.unbindAll(el);
|
||||
|
||||
var html;
|
||||
@@ -81,8 +85,10 @@ function renderDependency(dep) {
|
||||
var $head = $("head").first();
|
||||
|
||||
if (dep.meta) {
|
||||
var metas = $.map(asArray(dep.meta), function(content, name) {
|
||||
return $("<meta>").attr("name", name).attr("content", content);
|
||||
var metas = $.map(asArray(dep.meta), function(obj, idx) {
|
||||
// only one named pair is expected in obj as it's already been decomposed
|
||||
var name = Object.keys(obj)[0];
|
||||
return $("<meta>").attr("name", name).attr("content", obj[name]);
|
||||
});
|
||||
$head.append(metas);
|
||||
}
|
||||
|
||||
@@ -663,7 +663,9 @@ var ShinyApp = function() {
|
||||
// render the HTML and deps to a null target, so
|
||||
// the side-effect of rendering the deps, singletons,
|
||||
// and <head> still occur
|
||||
exports.renderHtml($([]), message.content.html, message.content.deps);
|
||||
console.warn('The selector you chose ("' + message.selector +
|
||||
'") could not be found in the DOM.');
|
||||
exports.renderHtml(message.content.html, $([]), message.content.deps);
|
||||
} else {
|
||||
targets.each(function (i, target) {
|
||||
exports.renderContent(target, message.content, message.where);
|
||||
@@ -840,12 +842,22 @@ var ShinyApp = function() {
|
||||
|
||||
// Returns a URL which can be queried to get values from inside the server
|
||||
// function. This is enabled with `options(shiny.testmode=TRUE)`.
|
||||
this.getTestEndpointUrl = function() {
|
||||
return "session/" +
|
||||
this.getTestSnapshotBaseUrl = function({ fullUrl = true } = {})
|
||||
{
|
||||
const loc = window.location;
|
||||
let url = "";
|
||||
|
||||
if (fullUrl) {
|
||||
// Strip off everything after last slash in path, like dirname() in R
|
||||
url = loc.origin + loc.pathname.replace(/\/[^/]*$/, "");
|
||||
}
|
||||
url += "/session/" +
|
||||
encodeURIComponent(this.config.sessionId) +
|
||||
"/dataobj/shinytest?w=" +
|
||||
encodeURIComponent(this.config.workerId) +
|
||||
"&nonce=" + randomId();
|
||||
|
||||
return url;
|
||||
};
|
||||
|
||||
}).call(ShinyApp.prototype);
|
||||
|
||||
@@ -976,3 +976,83 @@ test_that("event handling helpers take correct dependencies", {
|
||||
expect_equal(execCount(o1), 2)
|
||||
expect_equal(execCount(o2), 2)
|
||||
})
|
||||
|
||||
run_debounce_throttle <- function(do_priming) {
|
||||
# The changing of rv$a will be the (chatty) source of reactivity.
|
||||
rv <- reactiveValues(a = 0)
|
||||
|
||||
# This observer will be what changes rv$a.
|
||||
src <- observe({
|
||||
invalidateLater(100)
|
||||
rv$a <- isolate(rv$a) + 1
|
||||
})
|
||||
on.exit(src$destroy(), add = TRUE)
|
||||
|
||||
# Make a debounced reactive to test.
|
||||
dr <- debounce(reactive(rv$a), 500)
|
||||
|
||||
# Make a throttled reactive to test.
|
||||
tr <- throttle(reactive(rv$a), 500)
|
||||
|
||||
# Keep track of how often dr/tr are fired
|
||||
dr_fired <- 0
|
||||
dr_monitor <- observeEvent(dr(), {
|
||||
dr_fired <<- dr_fired + 1
|
||||
})
|
||||
on.exit(dr_monitor$destroy(), add = TRUE)
|
||||
|
||||
tr_fired <- 0
|
||||
tr_monitor <- observeEvent(tr(), {
|
||||
tr_fired <<- tr_fired + 1
|
||||
})
|
||||
on.exit(tr_monitor$destroy(), add = TRUE)
|
||||
|
||||
# Starting values are both 0. Earlier I found that the tests behaved
|
||||
# differently if I accessed the values of dr/tr before the first call to
|
||||
# flushReact(). That bug was fixed, but to ensure that similar bugs don't
|
||||
# appear undetected, we run this test with and without do_priming.
|
||||
if (do_priming) {
|
||||
expect_identical(isolate(dr()), 0)
|
||||
expect_identical(isolate(tr()), 0)
|
||||
}
|
||||
|
||||
# Pump timer and reactives for about 1.4 seconds
|
||||
stopAt <- Sys.time() + 1.4
|
||||
while (Sys.time() < stopAt) {
|
||||
timerCallbacks$executeElapsed()
|
||||
flushReact()
|
||||
Sys.sleep(0.001)
|
||||
}
|
||||
|
||||
# dr() should not have had time to fire, other than the initial run, since
|
||||
# there haven't been long enough gaps between invalidations.
|
||||
expect_identical(dr_fired, 1)
|
||||
# The value of dr() should not have updated either.
|
||||
expect_identical(isolate(dr()), 0)
|
||||
|
||||
# tr() however, has had time to fire multiple times and update its value.
|
||||
expect_identical(tr_fired, 3)
|
||||
expect_identical(isolate(tr()), 10)
|
||||
|
||||
# Now let some time pass without any more updates.
|
||||
src$destroy() # No more updates
|
||||
stopAt <- Sys.time() + 1
|
||||
while (Sys.time() < stopAt) {
|
||||
timerCallbacks$executeElapsed()
|
||||
flushReact()
|
||||
Sys.sleep(0.001)
|
||||
}
|
||||
|
||||
# dr should've fired, and we should have converged on the right answer.
|
||||
expect_identical(dr_fired, 2)
|
||||
isolate(expect_identical(rv$a, dr()))
|
||||
expect_identical(tr_fired, 4)
|
||||
isolate(expect_identical(rv$a, tr()))
|
||||
}
|
||||
|
||||
test_that("debounce/throttle work properly (with priming)", {
|
||||
run_debounce_throttle(TRUE)
|
||||
})
|
||||
test_that("debounce/throttle work properly (without priming)", {
|
||||
run_debounce_throttle(FALSE)
|
||||
})
|
||||
|
||||
@@ -129,6 +129,31 @@ test_that("anyUnnamed works as expected", {
|
||||
expect_true(anyUnnamed(x))
|
||||
})
|
||||
|
||||
test_that("sortByName works as expected", {
|
||||
# Error if any unnamed elements
|
||||
expect_error(sortByName(c("a", "b")))
|
||||
expect_error(sortByName(list(a=1, 2)))
|
||||
|
||||
expect_identical(sortByName(NULL), NULL)
|
||||
expect_identical(sortByName(numeric(0)), numeric(0))
|
||||
expect_identical(sortByName(character(0)), character(0))
|
||||
# Empty unnamed list
|
||||
expect_identical(sortByName(list()), list())
|
||||
# Empty named list
|
||||
expect_identical(sortByName(list(a=1)[0]), list(a=1)[0])
|
||||
|
||||
expect_identical(sortByName(list(b=1, a=2)), list(a=2, b=1))
|
||||
expect_identical(sortByName(list(b=1)), list(b=1))
|
||||
|
||||
# Ties are resolved by using original order
|
||||
expect_identical(sortByName(list(b=1, a=2, b=3)), list(a=2, b=1, b=3))
|
||||
expect_identical(sortByName(list(b=3, a=2, b=1)), list(a=2, b=3, b=1))
|
||||
|
||||
# Make sure atomic vectors work
|
||||
expect_identical(sortByName(c(b=1, a=2)), c(a=2, b=1))
|
||||
expect_identical(sortByName(c(b=1, a=2, b=3)), c(a=2, b=1, b=3))
|
||||
})
|
||||
|
||||
test_that("Callbacks fire in predictable order", {
|
||||
cb <- Callbacks$new()
|
||||
|
||||
|
||||
@@ -10,11 +10,7 @@ Shiny's JavaScript build tools use Node.js, along with [yarn](https://yarnpkg.co
|
||||
|
||||
Installation of Node.js differs across platforms and is generally pretty easy, so I won't include instructions here.
|
||||
|
||||
There are a number of ways to [install yarn](https://yarnpkg.com/en/docs/install), but if you already have npm installed, you can simply run:
|
||||
|
||||
```
|
||||
sudo npm install --global yarn
|
||||
```
|
||||
Install yarn using the [official instructions](https://yarnpkg.com/en/docs/install).
|
||||
|
||||
Then, in this directory (tools/), run the following to install the packages:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user