Skip to content

keller-mark/anyhtmlwidget

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

8473ed7 · Jul 10, 2024

History

35 Commits
May 28, 2024
Jun 18, 2024
Jul 10, 2024
May 28, 2024
May 28, 2024
Jun 18, 2024
Jun 18, 2024
Jun 18, 2024
Jun 14, 2024
May 17, 2024
May 17, 2024
May 28, 2024
May 28, 2024
May 16, 2024

Repository files navigation

anyhtmlwidget

Bringing core concepts from anywidget to R.

  • Define widget as a JavaScript EcmaScript Module (ESM) string in R
  • Access state from JS using the same AnyWidget model API.
  • Bidirectional communication (R <-> JS)

Installation

devtools::install_github("keller-mark/anyhtmlwidget")

Usage

library(anyhtmlwidget)

esm <- "
function render({ el, model }) {
  let count = () => model.get('count');
  let btn = document.createElement('button');
  btn.innerHTML = `count button ${count()}`;
  btn.addEventListener('click', () => {
    model.set('count', count() + 1);
    model.save_changes();
  });
  model.on('change:count', () => {
        btn.innerHTML = `count is ${count()}`;
  });
  el.appendChild(btn);
}
export default { render };
"

widget <- AnyHtmlWidget$new(.esm = esm, .mode = "dynamic", count = 1)
widget$render()

Setting a value will cause a re-render:

widget$count <- 2

Access the latest values:

widget$count
# [1] 2

Modes

  • dynamic: Bidirectional communication via background WebSocket server. Does not block R console.
  • gadget: Bidirectional communication via Shiny running as a Gadget. Blocks R console.
  • static: Unidirectional communication (R -> JS). Does not block R console.
  • shiny: Bidirectional communication. Use when embedding a widget in a Shiny app.