Bug Report: Layout gets pushed around

In https://beta.observablehq.com/@domoritz/global-development-example-in-vega, the chart pushes some cells down so that they don’t line up with the controls on the left anymore.

This is because Vega is setting the height of the DIV asynchronously after it is returned. This behavior is discussed in the Introduction to HTML notebook. Short of changing Vega to set the height synchronously, here are two ways to deal with dynamically-resizing content in Observable.

The first way is to yield twice:

{
  var div = document.createElement("div");
  var loader = vega.loader({baseURL: 'https://vega.github.io/vega/'});
  (new vega.View(vega.parse(vegaSpec), {loader: loader})).initialize(div).run();
  yield div;
  yield div;
}

The first yield will have the wrong height (because Vega hasn’t finished drawing the chart yet), while the second yield will have the desired height.

The second, more explicit, way is to dispatch an update event after yielding the DIV, so that Observable knows that its height has changed:

{
  var div = document.createElement("div");
  var loader = vega.loader({baseURL: 'https://vega.github.io/vega/'});
  (new vega.View(vega.parse(vegaSpec), {loader: loader})).initialize(div).run();
  yield div;
  div.dispatchEvent(new CustomEvent("update"));
}

Edit: I think it might be more complicated than dispatching immediately after the first yield (or immediately yielding again)—you might need to wait for Vega to load gapminder.json or whatever else it is doing asynchronously.

Ah, try view.runAsync:

{
  var div = document.createElement("div");
  var loader = vega.loader({baseURL: 'https://vega.github.io/vega/'});
  await new vega.View(vega.parse(vegaSpec), {loader: loader}).initialize(div).runAsync();
  return div;
}

Thank Mike! This definitely works better for the example I am using. However, it is not a general fix as a chart might resize because of interactions or signal changes.

I think the right fix is to listen for dataflow runs or resize events. The latter would only run when it is actually necessary to update the cell’s height. I created an issue for that at https://github.com/vega/vega/issues/1120

You’re very welcome, and thanks for filing the issue! A web standard for observing resizes would certainly be fantastic! Unfortunately polling all cells continuously isn’t viable for performance reasons, though possibly there are clever heuristics we could employ to do it selectively.