d3 layout test

by Yoshiharu Kamata

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<svg width="100%" height="600px" viewBox="0 0 800 600"></svg>

CSS

svg g.node rect {
  fill: lightgray;
  stroke: gray;
}
svg g.node.select rect {
  stroke: red;
}
svg g.node.sonar rect {
  stroke: black;
  fill:   yellow;
}

CoffeeScript

console.log "start"
db = 
  resources: {}
  ch: []
  psvr: []
  lsvr: []
  lpf: []
  t: []
window.db = db
class Resource
  type: "resource"
  name: ""
  width: 50
  height: 50
  rx: 5
  ry: 5
  layer: 0
  constructor: (attr)->
    _.extend @, attr
    @_children = []
    @_parents = {}
    @_links =
      left: []
      right: []
    @id = _.uniqueId()
    db.resources[@id] = @
    @
  addChild: (child)->
    child._parents[@type] = @id
    @_children.push child.id
    @
    
  addLeft: (other)->
    @_links.left.push other
    other._links.right.push @
    
  addRight: (other)->
    @_links.right.push other
    other._links.left.push @
  
  left: ->
    @_links.left
  right: ->
    @_links.right
  leftAll: ->
    @links "left"
  rightAll: ->
    @links "right"
  
  linksBoth: ->
    _.union @links("left"), @links("right")
  siblings: ->
    left = _(@left())
    .map (item)->
      item.right()
    .flatten()
    .valueOf()
    
    right = _(@right())
    .map (item)->
      item.left()
    .flatten()
    .valueOf()
    
    _(right).union(left).uniq().valueOf()
    
  links: (dir)->
    links = @[dir]()
    if _.isEmpty links
      []
    else
      _(links).map (link)->
        link.links dir
      .flatten()
      .union(links)
      .uniq()
      .valueOf()
        
  parent: (type)->
    db.resources[@parents[type]]
  children: ->
    _.map @_children, (id)->
      db.resources[id]
  childrenLink: ->
    _(@children()).map (child)=>
      _(child._parents).reject (id, type)=>
        type == @type
      .map (id)->
        db.resources[id]
      .valueOf()
    .flatten()
    .valueOf()
    
  descendants: ->
    children = @children()
    if _.isEmpty children
      []
    else
      _(children).map (child)->
        child.descendants()
      .flatten()
      .union(children)
      .valueOf()
        
  ancestors: (options)->
    reject = options?.reject
    console.log "r=",reject
    parents = _(@_parents).map (id)->
      db.resources[id]
    .reject...