d3-legend: NS_ERROR_FAILURE errors

Hello there,

I keep encountering NS_ERROR_FAILURE errors when using d3-legend. Here’s an Observable notebook, which tries to recreate the Linear Scale Legend - Horizontal example.

I tried to recreate the example outside of an Observable notebook and encountered the same errors. Is it possible that there is an issue with the package?

Thanks in advance,

Iain

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (5 by maintainers)

Most upvoted comments

Okay, pretty simple fix:

{
  const svg = d3.select(DOM.svg(width, 40));
  yield svg.node();
  svg.append("g").call(legend);
}

https://beta.observablehq.com/@mbostock/d3-legend

The issue is that d3-svg-legend depends on the SVG node being added to the DOM before you call it, and in Observable, things aren’t added to the DOM until the cell yields or returns. Specifically, you’re using element.getBBox on the text and shape elements generated by the legend, but since the SVG node hasn’t yet been added to the document, the bounding boxes can’t be computed—they are dependent on the styles that the SVG element will inherit, which isn’t known until the SVG element is added to the body.

Probably want you want to do is to have d3-svg-legend through an error if the element that you apply it to isn’t in the DOM. That would be something like this…

svg.each(function() {
  if (!this.ownerDocument.contains(this)) {
    throw new Error("cannot generate legend on detached element");
  }
});