{"id":13718300,"url":"https://github.com/hrbrmstr/lit-webr","last_synced_at":"2026-05-09T06:10:31.567Z","repository":{"id":219813890,"uuid":"618883080","full_name":"hrbrmstr/lit-webr","owner":"hrbrmstr","description":"🧪 🕸️ An example of using WebR with Lit components","archived":false,"fork":false,"pushed_at":"2023-03-26T10:42:15.000Z","size":103,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"batman","last_synced_at":"2025-01-16T02:47:29.380Z","etag":null,"topics":["lit-element","lit-html","r","rstats","web-components","webr","webr-experiment"],"latest_commit_sha":null,"homepage":"https://rud.is/w/lit-webr/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hrbrmstr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-25T16:19:00.000Z","updated_at":"2023-12-06T23:27:53.000Z","dependencies_parsed_at":null,"dependency_job_id":"e47bdabb-bed6-40c5-bfb3-98d8f13f4cc7","html_url":"https://github.com/hrbrmstr/lit-webr","commit_stats":null,"previous_names":["hrbrmstr/lit-webr"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hrbrmstr%2Flit-webr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hrbrmstr%2Flit-webr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hrbrmstr%2Flit-webr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hrbrmstr%2Flit-webr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hrbrmstr","download_url":"https://codeload.github.com/hrbrmstr/lit-webr/tar.gz/refs/heads/batman","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242039718,"owners_count":20061928,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["lit-element","lit-html","r","rstats","web-components","webr","webr-experiment"],"created_at":"2024-08-03T01:00:22.452Z","updated_at":"2026-05-09T06:10:26.545Z","avatar_url":"https://github.com/hrbrmstr.png","language":"JavaScript","funding_links":[],"categories":["Community Demos"],"sub_categories":["Miscellaneous"],"readme":"# 🧪 Lit + WebR\n\n\u003eSee it [live](https://rud.is/w/lit-webr/) before reading!\n\n## Linking Lit's Lightweight Web Components And WebR For Vanilla JS Reactivity\n\n### This is a Lit + WebR reproduction of the [OG Shiny Demo App](https://shiny.rstudio.com/gallery/telephones-by-region.html)\n\n[Lit](https://lit.dev/) is a javascript library that makes it a bit easier to work with [Web Components](https://dailyfinds.hrbrmstr.dev/p/drop-227-2023-03-24-weekend-project), and is especially well-suited in reactive environments.\n\nMy recent hack-y WebR experiments have been using [Reef](https://reefjs.com/getting-started/) which is an _even ligher_-weight javascript web components-esque library, and it's a bit more (initially) accessible than Lit. Lit's focus on \"Web Components-first\" means that you are kind of forced into a structure, which is good, since reactive things can explode if not managed well.\n\nI also think this might Shiny folks feel a bit more at home.\n\nThis is the structure of our Lit + WebR example _(I keep rejiggering this layout, which likely frustrates alot of folks_ 🙃)_\n\n```console\nlit-webr\n├── css\n│   └── style.css             # you know what this is\n├── favicon.ico               # when developing locally I want my icon\n├── index.html                # you know what this is\n├── main.js                   # the core experiment runner\n├── md\n│   └── main.md               # the core experiment markdown file\n├── r-code\n│   └── region-plot.R         # we keep longer bits of R code in source files here\n├── r.js                      # place for WebR work\n├── renderers.js              # these experiment templates always use markdown\n├── themes\n│   └── ayu-dark.json         # my fav shiki theme\n├── utils.js                  # handy utilities (still pretty bare)\n├── wc\n│   ├── region-plot.js        # 👉🏼 WEB COMPONENT for the plot\n│   ├── select-list.js        # 👉🏼               for the regions popup menu\n│   └── status-message.js     # 👉🏼               for the status message\n├── webr-serviceworker.js.map # not rly necessary; just for clean DevTools console\n└── webr-worker.js.map        # ☝🏽\n```\n\nA great deal has changed (due to using Lit) since the last time you saw one of these experiments. You should [scan through the source](https://github.com/hrbrmstr/lit-webr) before continuing.\n\nThe core changes to `index.html` are just us registering our web components:\n\n```html\n\u003cscript type=\"module\" src=\"./wc/select-list.js\"\u003e\u003c/script\u003e\n\u003cscript type=\"module\" src=\"./wc/region-plot.js\"\u003e\u003c/script\u003e\n\u003cscript type=\"module\" src=\"./wc/status-message.js\"\u003e\u003c/script\u003e\n```\n\nWe _could_ have rolled them up into one JS file and minified them, but we're keeping things simple for these experiments. \n\nWeb Components (\"components\" from now on) become an \"equal citizen\" in terms of `HTMLElements`, and they're registered right in the DOM.\n\nThe next big change is in this file (the rendered `main.md`), where we use these new components instead of our `\u003cdiv\u003e`s. The whittled down version of it is essentially:\n\n```html\n\u003cstatus-message id=\"status\"\u003e\u003c/status-message\u003e\n\n\u003cregion-plot id=\"regionsOutput\" svgId=\"lit-regions\"\u003e\n  \u003cselect-list label=\"Select a region:\" id=\"regionsInput\"\u003e\u003c/select-list\u003e\n\u003c/region-plot\u003e\n```\n\nThe _intent_ of those elements is pretty clear (much clearer than the `\u003cdiv\u003e` versions), which is one aspect of components I like quite a bit.\n\nYou'll also notice components are `-` (dash) crazy. That's part of the Web Components spec and is mandatory.\n\nWe're using pretty focused components. What I mean by that is that they're not very reusable across other projects without copy/paste. Part of that is on me since I don't do web stuff for a living. Part of it was also to make it easier to show how to use them with WebR.\n\nWith more modular code, plus separating out giant chunks of R source means that we can actually put the entirety of `main.js` right here _(I've removed all the annotations; please look at `main.js` to see them; we will be explaining one thing in depth here, vs there, tho.)_:\n\n```js\nimport { renderMarkdownInBody } from \"./renderers.js\";\nimport * as d3 from \"https://cdn.jsdelivr.net/npm/d3@7/+esm\";\n\nawait renderMarkdownInBody(\n  `main`,\n  \"ayu-dark\",\n  [ 'javascript', 'r', 'json', 'md', 'xml', 'console' ],\n  false\n)\n\nlet message = document.getElementById(\"status\");\nmessage.text = \"WebR Loading…\"\n\nimport * as R from \"./r.js\";\n\nmessage.text = \"Web R Initialized!\"\n\nawait R.webR.installPackages([ \"svglite\" ])\n\nawait R.library(`svglite`)\nawait R.library(`datasets`)\n\nconst regionRender = await globalThis.webR.evalR(await d3.text(\"r-code/region-plot.R\"))\n\nmessage.text = \"{svglite} installed\"\n\nconst regions = document.getElementById(\"regionsInput\")\nconst plotOutput = document.getElementById(\"regionsOutput\")\n\nregions.options = await (await R.webR.evalR(`colnames(WorldPhones)`)).toArray()\nplotOutput.region = regions.options[ 0 ]\nplotOutput.renderFunction = regionRender\nplotOutput.render()\n\nmessage.text = \"Ready\"\n```\n\nI want to talk a bit about this line from `main.js`:\n\n```js\nconst regionRender = await globalThis.webR.evalR(\n  await d3.text(\"r-code/region-plot.R\")\n)\n```\n\nThat fetches the source of the single R file we have in this app, evaluates it, and returns the evaluated value (which is an R `function` object) to javascript. This is the script:\n\n```r\nrenderRegions \u003c- function(region, id = \"region-plot\") {\n\n  # our base plot theme\n\n  list(\n    panel.fill = \"#001e38\",\n    bar.fill = \"#4a6d88\",\n    axis.color = \"#c6cdd7\",\n    label.color = \"#c6cdd7\",\n    subtitle.color = \"#c6cdd7\",\n    title.color = \"#c6cdd7\",\n    ticks.color = \"#c6cdd7\",\n    axis.color = \"#c6cdd7\"\n  ) -\u003e theme\n\n  # get our svg graphics device amp'd\n  s \u003c- svgstring(width = 8, height = 4, pointsize = 8, id = id, standalone = FALSE)\n\n  # setup theme stuff we can't do in barplot()\n  par(\n    bg = theme$panel.fill,\n    fg = theme$label.color\n  )\n\n  # um, it's a barplot\n  barplot(\n    WorldPhones[, region],\n    main = region,\n    col = theme$bar.fill,\n    sub = \"Data from AT\u0026T (1961) The World's Telephones\",\n    ylab = \"Number of Telephones (K)\",\n    xlab = \"Year\",\n    border = NA,\n    col.axis = theme$axis.color,\n    col.lab = theme$label.color,\n    col.sub = theme$subtitle.color,\n    col.main = theme$title.color\n  )\n\n  dev.off()\n\n  # get the stringified SVG\n  plot_svg \u003c- s()\n\n  # make it responsive\n  plot_svg \u003c- sub(\"width='\\\\d+(\\\\.\\\\d+)?pt'\", \"width='100%'\", plot_svg)\n  plot_svg \u003c- sub(\"height='\\\\d+(\\\\.\\\\d+)?pt'\", \"\", plot_svg)\n\n  # return it\n  plot_svg\n  \n}\n```\n\nThat R function is callable _right from javascript_. Creating that ability was super brilliant of George (the Godfather of WebR). We actually end up giving it to the component that plots the barplot (see `region-plot.js`) right here:\n\n```js\nplotOutput.renderFunction = regionRender\n```\n\nWe're getting a bit ahead of ourselves, since we haven't talked about the components yet. We'll do so, starting with the easiest one to grok, which is in `status-message.js` and is represented by the `\u003cstatus-message\u003e\u003c/status-message\u003e` tag.\n\nThese custom Lit components get everything `HTMLElement` has, plus whatever else you provide. I'm not going to show the entire source for `status-message.js` here as it is (lightly) annotated. We'll just cover the fundamentals, as Lit components also have alot going on and we're just using a fraction of what they can do. Here's the outline of what's in our `status-message`:\n\n```js\nexport class StatusMessage extends LitElement {\n  static properties = { /* things you can assign to and read from */ }\n  static styles = [ /* component-scoped CSS */ ]\n  constructor() { /* initialization bits */\n  render() { /* what gets called when things change */ }\n}\n// register it\ncustomElements.define('status-message', StatusMessage);\n```\n\nOur `status-message` `properties` just has one property:\n\n```js\nstatic properties = {\n  text: {type: String}, // TypeScript annotations are requried by Lit\n};\n```\n\nThis means when we do:\n\n```js\nlet message = document.getElementById(\"status\");\nmessage.text = \"WebR Loading…\"\n```\n\nwe are finding our component in the DOM, then updating the property we defined. That will trigger `render()` each time, and use any component-restricted CSS we've setup.\n\nThings get a _tad more complicated_ in `select-list.js`. We'll just cover the highlights, starting with the `properties`:\n\n```js\nstatic properties = {\n  id: { type: String },    // gives us easy access to the id we set\n  label: { type: String }, // lets us define the label up front\n  options: { type: Array } // where the options for the popup will go\n};\n```\n\nIf you recall, this is how we used them in the source:\n\n```html\n\u003cregion-plot id=\"regionsOutput\" svgId=\"lit-regions\"\u003e\n  \u003cselect-list label=\"Select a region:\" id=\"regionsInput\"\u003e\u003c/select-list\u003e\n\u003c/region-plot\u003e\n```\n\nThe `id` and `label` properties will be available right away after the custom element creation.\n\nWe start `option` with an empty list:\n\n```js\nconstructor() {\n  super()\n  this.options = []\n}\n```\n\nOur `render()` function places the `\u003clabel\u003e` and `\u003cselect\u003e` tags in the DOM and will eventually populate the menu once it has data:\n\n```js\nrender() {\n  const selectId = `select-list-${this.id}`;\n  return html`\n  \u003clabel for=\"${selectId}\"\u003e${this.label} \n    \u003cselect id=\"${selectId}\" @change=${this._dispatch}\u003e\n      ${this.options.map(option =\u003e html`\u003coption\u003e${option}\u003c/option\u003e`)}\n    \u003c/select\u003e\n  \u003c/label\u003e\n  `;\n}\n```\n\nTheir clever use of JS template strings makes it much easier than ugly string concatenation.\n\n\u003eThat `html` in the `return` is doing _alot_ of work, and not just returning text. You gotta read up on Lit to get more info b/c this is already too long.\n\nThe way we wired up reactivity in my Reef examples felt kludgy, and even the nicer way to do it in Reef feels kludgy to me. It's _really_ nice in Lit. This little addition to the `\u003cselect\u003e` tag:\n\n```js\n@change=${this._dispatch}\n```\n\nsays to call a function named `_dispatch` whenever the value changes. That's in the component as well:\n\n```js\n_dispatch(e) {\n  const options = {\n    detail: e.target,\n    bubbles: true,\n    composed: true,\n  };\n  this.dispatchEvent(new CustomEvent(`regionChanged`, options));\n}\n```\n\nWe setup a data structure and then fire off a custom event that our plot component will listen for.  We've just linked them together on one side. Now we just need to populate the `options` list, using some data from R:\n\n```js\nconst regions = document.getElementById(\"regionsInput\")\nregions.options = await (await R.webR.evalR(`colnames(WorldPhones)`)).toArray()\n```\n\nThat'll make the menu appear.\n\nHearkening back to the `main.js` plot setup:\n\n```js\nconst plotOutput = document.getElementById(\"regionsOutput\")\nplotOutput.region = regions.options[ 0 ]\nplotOutput.renderFunction = regionRender\nplotOutput.render()\n```\n\nwe see that we:\n\n- find the element\n- set the default region to the first one in the popup\n- assign our R-created rendering function to it\n- and ask it nicely to render right now vs wait for someone to select something\n  \nThe other side of that (`region-plot.js`) is a bit more complex. Let's start with the `properties`:\n\n```js\nstatic properties = {\n  // we keep a local copy for fun\n  region: { type: String },\n  \n  // this is where our S\n  asyncSvg: { type: String },\n  \n  // a DOM-accessible id string (cld be handy)\n  svgId: { type: String },\n\n  // the function to be called to render\n  renderFunction: { type: Function }\n};\n```\n\nWebR === \"async\", which is why you see that `asyncSvg`. Async is great and also a pain. There are way more functions in `region-plot.js` as a result.\n\nWe have to have something in `renderFunction` before WebR is powered up since the component will be alive before that. We'll give it an anonymous async function that returns an empty SVG.\n\n```js\nthis.renderFunction = async () =\u003e `\u003csvg\u003e\u003c/svg\u003e`\n```\n\nOddly enough, our `render` function _does not call the plotting function_. This is what it does:\n\n```js\nrender() {\n  return html`\n  \u003cdiv\u003e\n  \u003cslot\u003e\u003c/slot\u003e\n  ${unsafeSVG(this.asyncSvg)}\n  \u003c/div\u003e`;\n}\n```\n\nThis bit:\n\n```html\n\u003cslot\u003e\u003c/slot\u003e\n```\n\njust tells `render()` to take whatever is wrapped in the tag and shove it there (it's a bit more powerful than just that tho).\n\nThis bit:\n\n```js\n${unsafeSVG(this.asyncSvg)}\n```\n\nis just taking our string with SVG in it and letting Lit know we really want to live dangerously. Lit does its best to help you avoid security issues and SVGs are _dangerous_. \n\nSo, how _do_ we render the plot? With **two** new functions:\n\n```js\n// this is a special async callback mechanism that \n// lets the component behave normally, but do things \n// asynchronously when necessary.\nasync connectedCallback() {\n\n  super.connectedCallback();\n\n  // THIS IS WHERE WE CALL THE PLOT FUNCTION\n  this.asyncSvg = await this.renderFunction(this.region, this.svgId);\n\n  // We'll catch this event when the SELECT list changes or when\n  // WE fire it, like we do down below.\n  this.addEventListener('regionChanged', async (e) =\u003e {\n    this.region = e.detail.value;\n    const res = await this.renderFunction(this.region, this.svgId);\n    // if the result of the function call is from the R function and\n    // not the anonymous one we initialized the oject with\n    // we need to tap into the `values` slot that gets return\n    // with any call to WebR's `toJs()`\n    if (res.values) this.asyncSvg = res.values[ 0 ] ;\n  });\n\n}\n\n// special function that will get called when we \n// programmatically ask for a forced update\nperformUpdate() {\n  super.performUpdate();\n  const options = {\n    detail: { value: this.region },\n    bubbles: true,\n    composed: true,\n  };\n\n  // we fire the event so things happen async\n  this.dispatchEvent(new CustomEvent(`regionChanged`, options));\n}\n```\n\nThat finished the wiring up on the plotting end.\n\n## Serving 'Just' Desserts (Locally)\n\nI *highly* recommend using the tiny but awesome Rust-powered [miniserve](https://dailyfinds.hrbrmstr.dev/i/87467104/miniserve-rust) to serve things locally during development:\n\n```console\nminiserve \\\n  --header \"Cache-Control: no-cache; max-age=300\" \\\n  --header \"Cross-Origin-Embedder-Policy: require-corp\" \\\n  --header \"Cross-Origin-Opener-Policy: same-origin\" \\\n  --header \"Cross-Origin-Resource-Policy: cross-origin\" \\\n  --index index.html \\\n  .\n```\n\nYou can use that (once installed) from the local [justfile](https://github.com/casey/just), which (presently) has four semantically named actions:\n\n- install-miniserve\n- serve\n- rsync\n- github\n\nYou'll need to make path changes if you decide to use it.\n\n## FIN\n\nI realize this is quite a bit to take in, and — as I keep saying — most folks will be better off using WebR in Shiny (when available) or Quarto. \n\nLit gives us reactivity without the bloat that comes for the ride with Vue and React, so we get to stay in Vanilla JS land. You'll notice there's no \"npm\" or \"bundling\" or \"rollup\" here. You get to code in whatever environment you want, and serving WebR-powered pages is, then, as simple as an `rsync`.\n\nDrop issues at [the repo](https://github.com/hrbrmstr/lit-webr).\n\n\u003cp style=\"text-align:center;margin-top:2rem;\"\u003eBrought to you by @hrbrmstr\u003c/p\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhrbrmstr%2Flit-webr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhrbrmstr%2Flit-webr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhrbrmstr%2Flit-webr/lists"}