d3 / d3-drag

Drag and drop SVG, HTML or Canvas using mouse or touch input.
https://d3js.org/d3-drag
ISC License
332 stars 62 forks source link

Support d3.drag in testing environments #89

Open penx opened 1 year ago

penx commented 1 year ago

As per the report in https://github.com/d3/d3-drag/issues/79 which was closed without a fix.

If using d3-drag in a non browser environment, such as jest + testing-library, an error will be thrown:

    Error: Uncaught [TypeError: Cannot read property 'document' of null]

This comes from

https://github.com/d3/d3-drag/blob/c6a7e46c8d38aeac36adb18c0142d1944763e2c7/src/drag.js#L50-L63

https://github.com/d3/d3-drag/blob/c6a7e46c8d38aeac36adb18c0142d1944763e2c7/src/nodrag.js#L4-L5

Because view is null.

Downstream issues:

I think nodrag should return early if view is null:

export default function(view) {
  if(!view) {
    return;
  }
  var root = view.document.documentElement,
      selection = select(view).on("dragstart.drag", noevent, nonpassivecapture);
  if ("onselectstart" in root) {
    selection.on("selectstart.drag", noevent, nonpassivecapture);
  } else {
    root.__noselect = root.style.MozUserSelect;
    root.style.MozUserSelect = "none";
  }
}

...at least, this works for my use case. I'll raise a PR.