usethis::create_package("playground")
htmlwidgets::scaffoldWidget("play")
#>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.js1 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:
fs::dir_tree("JFR_Chapter5/playground")
├── DESCRIPTION
├── NAMESPACE
├── R
│ └── play.R
├── inst
│ └── htmlwidgets
│ ├── play.js
│ └── play.yaml
├── man
│ ├── play-shiny.Rd
│ └── play.Rd
└── playground.RprojThen, use document() (cmd+shift+Dcmd+shift+D) and load_all() (cmd+shift+Lcmd+shift+L) to document and load the package.
devtools::document()
devtools::load_all()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
play <- function(message, width = NULL, height = NULL, elementId = NULL) {
# forward options using x
x = list(
message = message
)
# create widget
htmlwidgets::createWidget(
name = '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
playOutput <- function(outputId, width = '100%', height = '400px'){
htmlwidgets::shinyWidgetOutput(outputId, 'play', width, height, package = 'playground')
}
#' @rdname play-shiny
#' @export
renderPlay <- function(expr, env = parent.frame(), quoted = FALSE) {
if (!quoted) { expr <- substitute(expr) } # force quoted
htmlwidgets::shinyRenderWidget(expr, playOutput, env, quoted = TRUE)
}