::create_package("playground")
usethis::scaffoldWidget("play")
htmlwidgets#>Created boilerplate for widget constructor R/play.R
#>Created boilerplate for widget dependencies at inst/htmlwidgets/play.yaml
#>Created boilerplate for widget javascript bindings at inst/htmlwidgets/play.js
1 JFR Chapter 5: Create a widget
This function puts together the minimalistic structure necessary to implement an htmlwidget and opens play.R
, play.js
, and play.yaml
in the RStudio IDE or the default text editor.
Here’s the directory structure for the project playground
:
::dir_tree("JFR_Chapter5/playground")
fs
├── DESCRIPTION
├── NAMESPACE
├── R
│ └── play.R
├── inst
│ └── htmlwidgets
│ ├── play.js
│ └── play.yaml
├── man-shiny.Rd
│ ├── play
│ └── play.Rd └── playground.Rproj
Then, use document()
(cmd+shift+Dcmd+shift+D) and load_all()
(cmd+shift+Lcmd+shift+L) to document and load the package.
::document()
devtools::load_all() devtools
There is only one function in the playground package, play()
, which is the constructor function for the widget. It takes a message as input and returns the message to HTML output.
play(message = "This is a widget!")
Click to see the source code of play.R
#' <Add Title>
#'
#' <Add Description>
#'
#' @import htmlwidgets
#'
#' @export
<- function(message, width = NULL, height = NULL, elementId = NULL) {
play
# forward options using x
= list(
x message = message
)
# create widget
::createWidget(
htmlwidgetsname = 'play',
x,width = width,
height = height,
package = 'playground',
elementId = elementId
)
}
#' Shiny bindings for play
#'
#' Output and render functions for using play within Shiny
#' applications and interactive Rmd documents.
#'
#' @param outputId output variable to read from
#' @param width,height Must be a valid CSS unit (like \code{'100\%'},
#' \code{'400px'}, \code{'auto'}) or a number, which will be coerced to a
#' string and have \code{'px'} appended.
#' @param expr An expression that generates a play
#' @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.
#'
#' @name play-shiny
#'
#' @export
<- function(outputId, width = '100%', height = '400px'){
playOutput ::shinyWidgetOutput(outputId, 'play', width, height, package = 'playground')
htmlwidgets
}
#' @rdname play-shiny
#' @export
<- function(expr, env = parent.frame(), quoted = FALSE) {
renderPlay if (!quoted) { expr <- substitute(expr) } # force quoted
::shinyRenderWidget(expr, playOutput, env, quoted = TRUE)
htmlwidgets }