Giter VIP home page Giter VIP logo

d4's Introduction

d4 -- Declarative Data-Driven Documents

What is it?

d4 is an experiment in using React to produce data-driven documents (ala d3) that are performant and understandable. This is not a library, but rather a demonstration that it's possible (and preferable) to use React instead of the core of d3.

Why?

d3 can produce fantastic results. Look no further than Mike Bostock's blocks for examples. Unfortunately, I always find d3 code surprisingly difficult to understand and extend, in the same way I used to find code difficult to approach before React encouraged a declarative style. By using React (which can render SVGs, no problem) for data-driven documents, we can improve comprehension and performance and use tools from the React ecosystem.

How does it work?

We replace the core d3 interaction of Enter, Update, Exit with, well, render. Let's first see an example.

d3

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.selectAll("path")
    .data(voronoi(samples).polygons())
  .enter().append("path")
    .attr("d", d => `M${d.join("L")}Z`)
    .style("fill", d => color(d.point))
    .style("stroke", d => color(d.point));

d4

function Mesh() {
  const paths = voronoi(samples)
    .polygons()
    .map(sample => (
      <path
        d={`M${sample.join('L')}Z`}
        fill={color(sample.data)}
        stroke={color(sample.data)}
      />
    ));

  return (
    <svg width={width} height={height}>
      {paths}
    </svg>
  );
}

We replace the mutating select, selectAll, enter, append, data, attr, and style with familiar React rendering of the points.

Animation is more complicated, but again, React can help. By using keys and the ReactCSSTransitionGroup, it's possible to describe animations in CSS, rather than using d3's interpolation. I haven't verified the performance, but I expect CSS transition group animations to be faster, since they're browser-native and avoid the JS engine. For example:

d3.select("body")
    .style("color", "green") // make the body green
  .transition()
    .style("color", "red"); // then transition to red

Becomes (specifying the duration, which the original left out):

body {
  transition: color 250ms;
}

Why we still need d3

d3 does a lot and we can continue to use most of it. In fact, these demos collectively use a dozen d3 packages. d3 is especially useful for calculating layouts and colors.

Future Work

There are some pieces of d3 that I would love to use but aren't easily portable. For example, d3-drag and d3-zoom smooth over a lot of the quirks you'd have to deal with when implementing dragging and zooming, but they're only designed to work with d3 selections (eg selection.call(d3.zoom().on("zoom", zoomed));).

I'm curious about the performance of this approach. I haven't benchmarked yet, but my intuition is that it should be fast -- as fast as React's reconciliation. However, I don't know how that part of d3 is implemented, so maybe d3 is actually faster.

A small thing -- it's possible to use only parts of d3. For example: import {voronoi as d3Voronoi} from 'd3-voronoi'; instead of d3.voronoi, and import {lab} from 'd3-color'; instead of d3.color.lab), but nobody uses it that way, so examples of the import style are hard to find (and it's often not obvious which name will be exported (d3-geo exports geoArea and geoBounds rather than area and bounds).

Besides the five completed demos, I've also started working on a few others, but I'm deferring them to get this article published.

Demos

In all the demos we continue to use some d3 utilities, but use React to separate the logic from the display declaration. Take a look at the source for a few!

d4's People

Contributors

joelburget avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

d4's Issues

missing `key` in the demonstration code

The demonstration code of https://d4.js.org shows the following example code:

const paths = voronoi(samples)
    .polygons()
    .map(sample => (
      <path
        d={`M${sample.join('L')}Z`}
        fill={color(sample.data)}
        stroke={color(sample.data)}
      />
    ));

but this is missing a key for React to do efficient DOM diffing. Without it you'll get both console warnings, and potentially slow operations where two samples being swapped causes React to instead rebuild them instead of just swapping them.

For properly taking advantage of React, you'll want something like this:

const paths = voronoi(samples)
    .polygons()
    .map(sample => (
      <path
        key={sample.id}
        d={`M${sample.join('L')}Z`}
        fill={color(sample.data)}
        stroke={color(sample.data)}
      />
    ));

where sample.id is a unique identifier for a sample.

And note that, while tempting, you can't use map( (sample,idx) => ....key={idx} ) because the sample's position in the list is not uniquely identifying for the sample (that's only unique information for the specific list the samples are currently in), so successive calls with a reordered array would still make React perform far worse than if a proper unique value is used as key.

Name confusion

Hey Joel,
There is already a project named D4 for charting with D3 https://github.com/heavysixer/d4

I just thought i'd bring that to your attention because I had users ask if I'd released a new version of the project when they came across yours. I am sure this will lead to name collisions of some form or another. My project already has the NPM namespace for D4 https://www.npmjs.com/package/d4 so you'll run into problems if you hope to deploy there.

Best Regards,
Mark

D3 v4.0 namespaced imports are actually encouraged

Hello,
there is a small inaccuracy in your documentation.
In the README you say:

A small thing β€” it's possible to use only parts of d3. For example: import {voronoi as d3Voronoi} from 'd3-voronoi'; instead of d3.voronoi, and import {lab} from 'd3-color'; instead of d3.color.lab), but nobody uses it that way, so examples of the import style are hard to find (and it's often not obvious which name will be exported (d3-geo exports geoArea and geoBounds rather than area and bounds).

Actually, the namespacing is a powerful feature and using it is encouraged in d3v4:

If you don’t care about modularity, you can mostly ignore this change and keep using the default bundle. However, there is one unavoidable consequence of adopting ES6 modules: every symbol in D3 4.0 now shares a flat namespace rather than the nested one of D3 3.x. For example, d3.scale.linear is now d3.scaleLinear, and d3.layout.treemap is now d3.treemap.

See the official migration guide (and specifically this namespace migration table for the d3-geo library)

Axes

Is there a good way to do axes in this paradigm?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.