d3 / d3-selection

Transform the DOM by selecting elements and joining to data.
https://d3js.org/d3-selection
ISC License
557 stars 292 forks source link

selection.appendAll #301

Open mbostock opened 2 years ago

mbostock commented 2 years ago

What if this

svg.append("g")
  .appendAll("rect", data)

were shorthand for this

svg.append("g")
  .selectAll()
  .data(data)
  .enter()
  .append("rect")

The latter is a common special case of the data-join, and it seems worthwhile to support it explicitly? Some optimizations:

Fil commented 2 years ago

Besides optimization, the benefit (as I understand it) would be a more straightforward expression of intent in that quite common case; a drawback might be that this new method doesn't allow the user to move from "create" to the "update" pattern if that's what they need.

curran commented 2 years ago

this new method doesn't allow the user to move from "create" to the "update" pattern if that's what they need.

That's a great point. Migrating code that is designed to be run only once to code that can be run multiple times is one of the biggest pain points of D3 (in my experience at least, this is what students especially struggle with the most).

Maybe the "update" pattern version of the shorthand could look something like this:

one(svg, "g")
  .joinAll("rect", data)

shorthand for

svg
  .selectAll("g")
  .data([null])
  .join("g")
  .selectAll()
  .data(data)
  .join("rect")
mbostock commented 2 years ago

Yes, that’s historically why D3 hasn’t included a special API for this case and encourages you to use selection.join instead. But I think it’s totally reasonable to special-case the enter selection, as people already do when they chain enter-append instead of using selection.join.