Title: | HTML Widgets for R |
---|---|
Description: | A framework for creating HTML widgets that render in various contexts including the R console, 'R Markdown' documents, and 'Shiny' web applications. |
Authors: | Ramnath Vaidyanathan [aut, cph], Yihui Xie [aut], JJ Allaire [aut], Joe Cheng [aut], Carson Sievert [aut, cre] , Kenton Russell [aut, cph], Ellis Hughes [ctb], Posit Software, PBC [cph, fnd] |
Maintainer: | Carson Sievert <[email protected]> |
License: | MIT + file LICENSE |
Version: | 1.6.4.9000 |
Built: | 2024-11-09 03:52:29 UTC |
Source: | https://github.com/ramnathv/htmlwidgets |
The htmlwidgets package provides a framework for easily creating R bindings to JavaScript libraries. Widgets created using the framework can be:
Used at the R console for data analysis just like conventional R plots (via RStudio Viewer)
Seamlessly embedded within R Markdown documents and Shiny web applications.
Saved as standalone web pages for ad-hoc sharing via email, Dropbox, etc.
To get started creating your own HTML widgets, see the documentation available in the package vignettes:
vignette("develop_intro", package = "htmlwidgets") vignette("develop_sizing", package = "htmlwidgets") vignette("develop_advanced", package = "htmlwidgets")
Source code for the package is available on GitHub:
https://github.com/ramnathv/htmlwidgets
Ramnath Vaidyanathan, Joe Cheng, JJ Allaire, and Yihui Xie
Create an HTML widget based on widget YAML and JavaScript contained within the specified package.
createWidget( name, x, width = NULL, height = NULL, sizingPolicy = htmlwidgets::sizingPolicy(), package = name, dependencies = NULL, elementId = NULL, preRenderHook = NULL )
createWidget( name, x, width = NULL, height = NULL, sizingPolicy = htmlwidgets::sizingPolicy(), package = name, dependencies = NULL, elementId = NULL, preRenderHook = NULL )
name |
Widget name (should match the base name of the YAML and JavaScript files used to implement the widget) |
x |
Widget instance data (underlying data to render and options that
govern how it's rendered). This value will be converted to JSON using
|
width |
Fixed width for widget (in css units). The default is
|
height |
Fixed height for widget (in css units). The default is
|
sizingPolicy |
Options that govern how the widget is sized in various
containers (e.g. a standalone browser, the RStudio Viewer, a knitr figure,
or a Shiny output binding). These options can be specified by calling the
|
package |
Package where the widget is defined (defaults to the widget name). |
dependencies |
Additional widget HTML dependencies (over and above those defined in the widget YAML). This is useful for dynamic dependencies that only exist when selected widget options are enabled (e.g. sets of map tiles or projections). |
elementId |
Use an explicit element ID for the widget (rather than an automatically generated one). Useful if you have other JavaScript that needs to explicitly discover and interact with a specific widget instance. |
preRenderHook |
A function to be run on the widget, just prior to rendering. It accepts the entire widget object as input, and should return a modified widget object. |
For additional details on developing widgets, see package vignettes:
vignette("develop_intro", package = "htmlwidgets")
.
An object of class htmlwidget
that will intelligently print
itself into HTML in a variety of contexts including the R console, within R
Markdown documents, and within Shiny output bindings.
Get js and css dependencies for a htmlwidget
getDependency(name, package = name)
getDependency(name, package = name)
name |
name of the widget. |
package |
name of the package, defaults to the widget name. |
Helpers to create output and render functions for using HTML widgets within Shiny applications and interactive Rmd documents.
shinyWidgetOutput( outputId, name, width, height, package = name, inline = FALSE, reportSize = TRUE, reportTheme = FALSE, fill = !inline ) shinyRenderWidget(expr, outputFunction, env, quoted, cacheHint = "auto")
shinyWidgetOutput( outputId, name, width, height, package = name, inline = FALSE, reportSize = TRUE, reportTheme = FALSE, fill = !inline ) shinyRenderWidget(expr, outputFunction, env, quoted, cacheHint = "auto")
outputId |
output variable to read from |
name |
Name of widget to create output binding for |
width , height
|
Must be a valid CSS unit (like |
package |
Package containing widget (defaults to |
inline |
use an inline ( |
reportSize |
Should the widget's container size be reported in the shiny session's client data? |
reportTheme |
Should the widget's container styles (e.g., colors and fonts) be reported in the shiny session's client data? |
fill |
whether or not the returned tag should be treated as a fill item,
meaning that its |
expr |
An expression that generates an HTML widget (or a promise of an HTML widget). |
outputFunction |
Shiny output function corresponding to this render function. |
env |
The environment in which to evaluate |
quoted |
Is |
cacheHint |
Extra information to use for optional caching using
|
These functions are delegated to from within your widgets own shiny output and render functions. The delegation is boilerplate and always works the same for all widgets (see example below).
An output or render function that enables the use of the widget within Shiny applications.
# shiny output binding for a widget named 'foo' fooOutput <- function(outputId, width = "100%", height = "400px") { htmlwidgets::shinyWidgetOutput(outputId, "foo", width, height) } # shiny render function for a widget named 'foo' renderFoo <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } # force quoted htmlwidgets::shinyRenderWidget(expr, fooOutput, env, quoted = TRUE) }
# shiny output binding for a widget named 'foo' fooOutput <- function(outputId, width = "100%", height = "400px") { htmlwidgets::shinyWidgetOutput(outputId, "foo", width, height) } # shiny render function for a widget named 'foo' renderFoo <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } # force quoted htmlwidgets::shinyRenderWidget(expr, fooOutput, env, quoted = TRUE) }
This function JS()
marks character vectors with a special class, so
that it will be treated as literal JavaScript code when evaluated on the
client-side.
JS(...)
JS(...)
... |
character vectors as the JavaScript source code (all arguments will be pasted into one character string) |
Yihui Xie
library(htmlwidgets) JS('1 + 1') list(x = JS('function(foo) {return foo;}'), y = 1:10) JS('function(x) {', 'return x + 1;', '}')
library(htmlwidgets) JS('1 + 1') list(x = JS('function(foo) {return foo;}'), y = 1:10) JS('function(x) {', 'return x + 1;', '}')
Use this function to supplement the widget's built-in JavaScript rendering logic with additional custom JavaScript code, just for this specific widget object.
onRender(x, jsCode, data = NULL)
onRender(x, jsCode, data = NULL)
x |
An HTML Widget object |
jsCode |
Character vector containing JavaScript code (see Details) |
data |
An additional argument to pass to the |
The jsCode
parameter must contain valid JavaScript code which
when evaluated returns a function.
The function will be invoked with three arguments: the first is the widget's
main HTML element, and the second is the data to be rendered (the x
parameter in createWidget
). The third argument is the JavaScript
equivalent of the R object passed into onRender
as the data
argument; this is an easy way to transfer e.g. data frames without having
to manually do the JSON encoding.
When the function is invoked, the this
keyword will refer to the
widget instance object.
The modified widget object
onStaticRenderComplete
, for writing custom JavaScript
that involves multiple widgets.
## Not run: library(leaflet) # This example uses browser geolocation. RStudio users: # this won't work in the Viewer pane; try popping it # out into your system web browser. leaflet() %>% addTiles() %>% onRender(" function(el, x) { // Navigate the map to the user's location this.locate({setView: true}); } ") # This example shows how you can make an R data frame available # to your JavaScript code. meh <- "😐"; yikes <- "😨"; df <- data.frame( lng = quakes$long, lat = quakes$lat, html = ifelse(quakes$mag < 5.5, meh, yikes), stringsAsFactors = FALSE ) leaflet() %>% addTiles() %>% fitBounds(min(df$lng), min(df$lat), max(df$lng), max(df$lat)) %>% onRender(" function(el, x, data) { for (var i = 0; i < data.lng.length; i++) { var icon = L.divIcon({className: '', html: data.html[i]}); L.marker([data.lat[i], data.lng[i]], {icon: icon}).addTo(this); } } ", data = df) ## End(Not run)
## Not run: library(leaflet) # This example uses browser geolocation. RStudio users: # this won't work in the Viewer pane; try popping it # out into your system web browser. leaflet() %>% addTiles() %>% onRender(" function(el, x) { // Navigate the map to the user's location this.locate({setView: true}); } ") # This example shows how you can make an R data frame available # to your JavaScript code. meh <- "😐"; yikes <- "😨"; df <- data.frame( lng = quakes$long, lat = quakes$lat, html = ifelse(quakes$mag < 5.5, meh, yikes), stringsAsFactors = FALSE ) leaflet() %>% addTiles() %>% fitBounds(min(df$lng), min(df$lat), max(df$lng), max(df$lat)) %>% onRender(" function(el, x, data) { for (var i = 0; i < data.lng.length; i++) { var icon = L.divIcon({className: '', html: data.html[i]}); L.marker([data.lat[i], data.lng[i]], {icon: icon}).addTo(this); } } ", data = df) ## End(Not run)
Convenience function for wrapping a JavaScript code string with a
<script>
tag and the boilerplate necessary to delay the execution of
the code until after the next time htmlwidgets completes rendering any
widgets that are in the page. This mechanism is designed for running code to
customize widget instances, which can't be done at page load time since the
widget instances will not have been created yet.
onStaticRenderComplete(jsCode)
onStaticRenderComplete(jsCode)
jsCode |
A character vector containing JavaScript code. No R error will be raised if the code is invalid, not even on JavaScript syntax errors. However, the web browser will throw errors at runtime. |
Each call to onStaticRenderComplete
will result in at most one
invocation of the given code. In some edge cases in Shiny, it's possible for
static rendering to happen more than once (e.g. a renderUI
that
contains static HTML widgets). onStaticRenderComplete
calls only
schedule execution for the next static render operation.
The pure JavaScript equivalent of onStaticRenderComplete
is
HTMLWidgets.addPostRenderHandler(callback)
, where callback
is a
JavaScript function that takes no arguments.
An htmltools tags$script
object.
## Not run: library(leaflet) library(htmltools) library(htmlwidgets) page <- tagList( leaflet() %>% addTiles(), onStaticRenderComplete( "HTMLWidgets.find('.leaflet').setZoom(4);" ) ) print(page, browse = TRUE) ## End(Not run)
## Not run: library(leaflet) library(htmltools) library(htmlwidgets) page <- tagList( leaflet() %>% addTiles(), onStaticRenderComplete( "HTMLWidgets.find('.leaflet').setZoom(4);" ) ) print(page, browse = TRUE) ## End(Not run)
Use these functions to attach extra HTML content (primarily JavaScript and/or CSS styles) to a widget, for rendering in standalone mode (i.e. printing at the R console) or in a knitr document. These functions are NOT supported when running in a Shiny widget rendering function, and will result in a warning if used in that context. Multiple calls are allowed, and later calls do not undo the effects of previous calls.
prependContent(x, ...) appendContent(x, ...)
prependContent(x, ...) appendContent(x, ...)
x |
An HTML Widget object |
... |
A modified HTML Widget object.
Save a rendered widget to an HTML file (e.g. for sharing with others).
saveWidget( widget, file, selfcontained = TRUE, libdir = NULL, background = "white", title = class(widget)[[1]], knitrOptions = list() )
saveWidget( widget, file, selfcontained = TRUE, libdir = NULL, background = "white", title = class(widget)[[1]], knitrOptions = list() )
widget |
Widget to save |
file |
File to save HTML into |
selfcontained |
Whether to save the HTML as a single self-contained file (with external resources base64 encoded) or a file with external resources placed in an adjacent directory. |
libdir |
Directory to copy HTML dependencies into (defaults to filename_files). |
background |
Text string giving the html background color of the widget. Defaults to white. |
title |
Text to use as the title of the generated page. |
knitrOptions |
A list of knitr chunk options. |
Add the minimal code required to implement an HTML widget to an R package.
scaffoldWidget(name, bowerPkg = NULL, edit = interactive())
scaffoldWidget(name, bowerPkg = NULL, edit = interactive())
name |
Name of widget |
bowerPkg |
Optional name of Bower package upon which this widget is based. If you specify this parameter then bower will be used to automatically download the widget's source code and dependencies and add them to the widget's YAML. |
edit |
Automatically open the widget's JavaScript source file after creating the scaffolding. |
This function must be executed from the root directory of the package you wish to add the widget to.
Set a random seed for generating widget element ids. Calling this function rather than relying on the default behavior ensures stable widget ids across sessions.
setWidgetIdSeed(seed, kind = NULL, normal.kind = NULL)
setWidgetIdSeed(seed, kind = NULL, normal.kind = NULL)
seed |
a single value, interpreted as an integer, or |
kind |
character or |
normal.kind |
character string or |
Define the policy by which HTML widgets will be sized in various containers (e.g. Browser, RStudio Viewer, R Markdown, Shiny). Note that typically widgets can accept the default sizing policy (or override only one or two aspects of it) and get satisfactory sizing behavior via the automatic sizing logic built into the htmlwidgets framework (see the notes below for the most typical exceptions to this).
sizingPolicy( defaultWidth = NULL, defaultHeight = NULL, padding = NULL, viewer.defaultWidth = NULL, viewer.defaultHeight = NULL, viewer.padding = NULL, viewer.fill = TRUE, viewer.suppress = FALSE, viewer.paneHeight = NULL, browser.defaultWidth = NULL, browser.defaultHeight = NULL, browser.padding = NULL, browser.fill = FALSE, browser.external = FALSE, knitr.defaultWidth = NULL, knitr.defaultHeight = NULL, knitr.figure = TRUE, fill = NULL )
sizingPolicy( defaultWidth = NULL, defaultHeight = NULL, padding = NULL, viewer.defaultWidth = NULL, viewer.defaultHeight = NULL, viewer.padding = NULL, viewer.fill = TRUE, viewer.suppress = FALSE, viewer.paneHeight = NULL, browser.defaultWidth = NULL, browser.defaultHeight = NULL, browser.padding = NULL, browser.fill = FALSE, browser.external = FALSE, knitr.defaultWidth = NULL, knitr.defaultHeight = NULL, knitr.figure = TRUE, fill = NULL )
defaultWidth |
The default width used to display the widget. This
parameter specifies the default width for viewing in all contexts (browser,
viewer, and knitr) unless it is specifically overridden with e.g.
|
defaultHeight |
The default height used to display the widget. This
parameter specifies the default height for viewing in all contexts
(browser, viewer, and knitr) unless it is specifically overridden with e.g.
|
padding |
Padding around the widget (in pixels). This parameter
specifies the padding for viewing in all contexts (browser and viewer)
unless it is specifically overriden by e.g. |
viewer.defaultWidth |
The default width used to display the widget within the RStudio Viewer. |
viewer.defaultHeight |
The default height used to display the widget within the RStudio Viewer. |
viewer.padding |
Padding around the widget when displayed in the RStudio Viewer (defaults to 15 pixels). |
viewer.fill |
When displayed in the RStudio Viewer, automatically size
the widget to the viewer dimensions (note that |
viewer.suppress |
Never display the widget within the RStudio Viewer
(useful for widgets that require a large amount of space for rendering).
Defaults to |
viewer.paneHeight |
Request that the RStudio Viewer be forced to a specific height when displaying this widget. |
browser.defaultWidth |
The default width used to display the widget within a standalone web browser. |
browser.defaultHeight |
The default height used to display the widget within a standalone web browser. |
browser.padding |
Padding around the widget when displayed in a standalone browser (defaults to 40 pixels). |
browser.fill |
When displayed in a standalone web browser, automatically
size the widget to the browser dimensions (note that |
browser.external |
When displaying in a browser, always use an external
browser (via |
knitr.defaultWidth |
The default width used to display the widget within documents generated by knitr (e.g. R Markdown). |
knitr.defaultHeight |
The default height used to display the widget within documents generated by knitr (e.g. R Markdown). |
knitr.figure |
Apply the default knitr fig.width and fig.height to the
widget when it's rendered within R Markdown documents. Defaults to
|
fill |
Whether or not the widget's container should be treated as a fill
item, meaning that its |
The default HTML widget sizing policy treats the widget with the same sizing semantics as an R plot. When printed at the R console the widget is displayed within the RStudio Viewer and sized to fill the Viewer pane (modulo any padding). When rendered inside an R Markdown document the widget is sized based on the default size of figures in the document.
You might need to change the default behavior if your widget is extremely
large. In this case you might specify viewer.suppress = TRUE
and
knitr.figure = FALSE
as well provide for a larger default width and
height for knitr.
You also might need to change the default behavior if you widget already
incorporates padding. In this case you might specify viewer.padding = 0
.
For additional details on widget sizing:
vignette("develop_sizing", package = "htmlwidgets")
A widget sizing policy