Notebook to Vanilla JavaScript Steps

You’re lucky, this particular example is really simple. In particular, it really only has one main visualization cell, and one data fetching cell and the rest are just helper functions / variables.

Here is a port to a “block”. To get to this, I worked roughly from bottom to top.

First, I added a script tags to index.html which import the d3 and d3-require libraries as well as the Observable standard library:

<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://unpkg.com/d3-require@1"></script>
<script src="https://cdn.jsdelivr.net/npm/@observablehq/stdlib"></script>

Next I added an svg element to serve as a target for the visualization:

  <svg id="packSVG" width=932 height=932 viewBox="0,0,932,932"></svg>

Then I added another script tag, and copied each of the notebook cells below data as functions / variables (making sure that the variables are defined in an order that makes sense):

<script>
const color = d3.scaleSequential(d3.interpolateMagma).domain([8, 0]);
const format = d3.format(",d");
const width = 932;
const height = width;
const pack = data => d3.pack()
    .size([width - 2, height - 2])
    .padding(3)
  (d3.hierarchy(data)
    .sum(d => d.size)
    .sort((a, b) => b.value - a.value));
</script>

The cell data fetches a file asynchronously, so we’ll have to wrap the rest of the code inside a promise. Put the following inside the above script tag.

d3.require('@observablehq/flare')
      .then(data => {
// add code here 
});

I then took the code from the main cell and copied it into the function inside then above, so that it will run after the data is successfully fetched.

The only changes I made were to change the main d3 selection from DOM.svg to a selector which picks out the target SVG element we added above, and then to comment out some references to DOM.uid in the standard library which weren’t working. The latter causes the text labels to spill outside the circles. I’ll see if I can figure out what’s going on with that later.

(By the way, it doesn’t look like you’ve changed anything from Mike Bostock’s notebook. Might you possibly have forgotten to share your edits?)

2 Likes