Type: | Package |
Title: | HTML Widgets for R |
Version: | 1.6.4 |
Description: | A framework for creating HTML widgets that render in various contexts including the R console, 'R Markdown' documents, and 'Shiny' web applications. |
License: | MIT + file LICENSE |
URL: | https://github.com/ramnathv/htmlwidgets |
BugReports: | https://github.com/ramnathv/htmlwidgets/issues |
Imports: | grDevices, htmltools (≥ 0.5.7), jsonlite (≥ 0.9.16), knitr (≥ 1.8), rmarkdown, yaml |
Suggests: | testthat |
Enhances: | shiny (≥ 1.1) |
VignetteBuilder: | knitr |
Encoding: | UTF-8 |
RoxygenNote: | 7.2.3 |
NeedsCompilation: | no |
Packaged: | 2023-12-06 00:11:16 UTC; cpsievert |
Author: | Ramnath Vaidyanathan [aut, cph],
Yihui Xie [aut],
JJ Allaire [aut],
Joe Cheng [aut],
Carson Sievert |
Maintainer: | Carson Sievert <carson@posit.co> |
Repository: | CRAN |
Date/Publication: | 2023-12-06 06:00:06 UTC |
HTML Widgets for R
Description
The htmlwidgets package provides a framework for easily creating R bindings to JavaScript libraries. Widgets created using the framework can be:
Details
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
Author(s)
Ramnath Vaidyanathan, Joe Cheng, JJ Allaire, and Yihui Xie
Create an HTML Widget
Description
Create an HTML widget based on widget YAML and JavaScript contained within the specified package.
Usage
createWidget(
name,
x,
width = NULL,
height = NULL,
sizingPolicy = htmlwidgets::sizingPolicy(),
package = name,
dependencies = NULL,
elementId = NULL,
preRenderHook = NULL
)
Arguments
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. |
Details
For additional details on developing widgets, see package vignettes:
vignette("develop_intro", package = "htmlwidgets")
.
Value
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
Description
Get js and css dependencies for a htmlwidget
Usage
getDependency(name, package = name)
Arguments
name |
name of the widget. |
package |
name of the package, defaults to the widget name. |
Shiny bindings for HTML widgets
Description
Helpers to create output and render functions for using HTML widgets within Shiny applications and interactive Rmd documents.
Usage
shinyWidgetOutput(
outputId,
name,
width,
height,
package = name,
inline = FALSE,
reportSize = TRUE,
reportTheme = FALSE,
fill = !inline
)
shinyRenderWidget(expr, outputFunction, env, quoted, cacheHint = "auto")
Arguments
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
|
Details
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).
Value
An output or render function that enables the use of the widget within Shiny applications.
Examples
# 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)
}
Mark character strings as literal JavaScript code
Description
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.
Usage
JS(...)
Arguments
... |
character vectors as the JavaScript source code (all arguments will be pasted into one character string) |
Author(s)
Yihui Xie
Examples
library(htmlwidgets)
JS('1 + 1')
list(x = JS('function(foo) {return foo;}'), y = 1:10)
JS('function(x) {', 'return x + 1;', '}')
Creates a list of keys whose values need to be evaluated on the client-side
Description
It works by transforming list(foo = list(1, list(bar =
I('function(){}')), 2))
to list("foo.2.bar")
. Later on the JS side,
the window.HTMLWidgets.evaluateStringMember
function is called with
the JSON object and the "foo.2.bar" string, which is split to ['foo',
'2', 'bar']
, and the string at that location is replaced in-situ with
the results of evaluating it. Note '2' (character) should have been 2
(integer) but it does not seem to matter in JS: x[2] is the same as x['2']
when all child members of x are unnamed, and ('2' in x) will be true even if
x is an array without names. This is a little hackish.
Usage
JSEvals(list)
Arguments
list |
a list in which the elements that should be evaluated as JavaScript are to be identified |
Details
This function is intended mostly for internal use. There's generally no need
for widget authors or users to call it, as it's called automatically on the
widget instance data during rendering. It's exported in case other packages
want to add support for JS
in contexts outside of widget
payloads.
Author(s)
Yihui Xie
Execute custom JavaScript code after rendering
Description
Use this function to supplement the widget's built-in JavaScript rendering logic with additional custom JavaScript code, just for this specific widget object.
Usage
onRender(x, jsCode, data = NULL)
Arguments
x |
An HTML Widget object |
jsCode |
Character vector containing JavaScript code (see Details) |
data |
An additional argument to pass to the |
Details
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.
Value
The modified widget object
See Also
onStaticRenderComplete
, for writing custom JavaScript
that involves multiple widgets.
Examples
## 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)
Execute JavaScript code after static render
Description
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.
Usage
onStaticRenderComplete(jsCode)
Arguments
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. |
Details
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.
Value
An htmltools tags$script
object.
Examples
## 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)
Prepend/append extra HTML content to a widget
Description
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.
Usage
prependContent(x, ...)
appendContent(x, ...)
Arguments
x |
An HTML Widget object |
... |
Value
A modified HTML Widget object.
Save a widget to an HTML file
Description
Save a rendered widget to an HTML file (e.g. for sharing with others).
Usage
saveWidget(
widget,
file,
selfcontained = TRUE,
libdir = NULL,
background = "white",
title = class(widget)[[1]],
knitrOptions = list()
)
Arguments
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. |
Create implementation scaffolding for an HTML widget
Description
Add the minimal code required to implement an HTML widget to an R package.
Usage
scaffoldWidget(name, bowerPkg = NULL, edit = interactive())
Arguments
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. |
Note
This function must be executed from the root directory of the package you wish to add the widget to.
Set the random seed for widget element ids
Description
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.
Usage
setWidgetIdSeed(seed, kind = NULL, normal.kind = NULL)
Arguments
seed |
a single value, interpreted as an integer, or |
kind |
character or |
normal.kind |
character string or |
Create a widget sizing policy
Description
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).
Usage
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
)
Arguments
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 |
Details
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")
Value
A widget sizing policy