JSFiddle - React, Tailwind, and code Playground

by Yoshiharu Kamata

HTML

<label for="crate-layer">Layer</label>
<select name="layer" id="create-layer">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<button id="create-btn">create</button>
<button id="connect-btn">connect</button>
<label for="layout">Layout</label>
<select name="layout" id="layout">
    <option value="layer">Layer</option>
    <option value="radial">Radial</option>
</select>
<svg width="300" height="300"></svg>

CoffeeScript

dataset = []
linkset = d3.set()
offset = {}
from = null
to = null
d3.select("#create-btn").on "click", ->
  layer = d3.select("#create-layer").node().value
  offset[layer] ||= 0
  offset[layer]++
  dataset.push
    layer: layer
    x: layer * 30 + 50
    y: offset[layer]*30 + 50
  update()
d3.select("#connect-btn").on "click", ->
  if from? and to? and from != to
    linkId = d3.extent([from, to]).join("_")
    linkset.add linkId
  from = null
  to = null
  update()
    
update = ->
  drawLine()
  d3.select("svg")
    .selectAll("circle")
    .data(dataset)
    .attr("stroke", (d, i)->
          if from == i
            "red"
          else if to == i
            "blue"
          else
            "orange"
          )
    .enter()
    .append("circle")
    .attr("cx", (d)-> d.x)
    .attr("cy", (d)-> d.y)
    .attr("r",10)
    .attr("fill", "yellow")
    .attr("stroke", "orange")
    .on("click", (d,i)->
        to = from 
        from = i
        update()
        )
drawLine = ->
  d3.select("svg")
    .selectAll("line")
    .data(linkset.values(), (d)-> d)
    .attr("x1", (d)-> dataset[d.split("_")[0]].x)
    .attr("y1", (d)-> dataset[d.split("_")[0]].y)
    .attr("x2", (d)-> dataset[d.split("_")[1]].x)
    .attr("y2", (d)-> dataset[d.split("_")[1]].y)
    .enter()
    .insert("line", ":first-child")
    .attr("x1", (d)-> dataset[d.split("_")[0]].x)
    .attr("y1", (d)-> dataset[d.split("_")[0]].y)
    .attr("x2", (d)-> dataset[d.split("_")[1]].x)
    .attr("y2", (d)-> dataset[d.split("_")[1]].y)
    .attr("stroke","orange")