+class PolylineWidget extends Widget
+ constructor: (args) ->
+ super args
+ @css_class = 'polyline'
+ @nodes = []
+ for n in args.nodes
+ @nodes.push x: n.x, y: n.y
+ @el = json_to_svg path:
+ d: @my_path_d()
+ class: 'polyline normal'
+ @svg.appendChild @el
+ destruct: ->
+ super()
+ if @el?
+ @svg.removeChild @el
+ clone: ->
+ return new PolylineWidget @
+ my_path_d: ->
+ ret = ''
+ for n in @nodes
+ if ret is ''
+ ret += 'M'
+ else
+ ret += 'L'
+ ret += n.x + @x
+ ret += ' '
+ ret += n.y + @y
+ return ret
+ set_state: (state) ->
+ super state
+ @update_class()
+ move: (args) ->
+ super args
+ @el.setAttribute 'd', @my_path_d()
+ @reposition_controls()
+ proximity: (xy) -> # return the square of the distance to your visible bits
+ prox = PROX_TOO_FAR
+ for n, i in @nodes
+ dx = @x + n.x - xy.x
+ dy = @y + n.y - xy.y
+ p = dx * dx + dy * dy
+ if p < prox
+ prox = p
+ if i > 0
+ l1x = @x + @nodes[i-1].x
+ l1y = @y + @nodes[i-1].y
+ l2x = @x + @nodes[i].x
+ l2y = @y + @nodes[i].y
+ ldx = l2x - l1x
+ ldy = l2y - l1y
+ if ldx is 0 # vertical line
+ if (xy.y < l1y) is (xy.y < l2y)
+ continue
+ dx = l1x - xy.x
+ p = dx * dx
+ else if ldy is 0 # horizontal line
+ if (xy.x < l1x) is (xy.x < l2x)
+ continue
+ dy = l1y - xy.y
+ p = dy * dy
+ else # slanty line
+ # https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
+ a = ldy
+ b = -1 * ldx
+ c = l2x * l1y - l2y * l1x
+ y_on_line = (a * (a * xy.y - b * xy.x) - b * c) / (a * a + b * b)
+ if (y_on_line < l1y) is (y_on_line < l2y)
+ continue
+ p = (a * xy.x + b * xy.y + c) / Math.sqrt(a * a + b * b)
+ p *= p
+
+ if p < prox
+ prox = p
+ return prox
+ resize: (wh) ->
+ # FIXME (apply to more than just 2nd node)
+ @nodes[1].x = wh.w
+ @nodes[1].y = wh.h
+ @width = wh.w
+ @height = wh.h
+ @el.setAttribute 'd', @my_path_d()
+ @reposition_controls()
+ return
+ node_dragger: (i) ->
+ if i is 0
+ return (dxy) =>
+ for i in [1...@nodes.length]
+ @nodes[i].x -= dxy.x
+ @nodes[i].y -= dxy.y
+ @move x: @x + dxy.x, y: @y + dxy.y
+ return (dxy) =>
+ @nodes[i].x += dxy.x
+ @nodes[i].y += dxy.y
+ @el.setAttribute 'd', @my_path_d()
+ @reposition_controls()
+ reposition_controls: ->
+ if @controls.length > 1
+ positions = @control_positions()
+ for i in [0...positions.length]
+ @controls[i].move x: positions[i].x, y: positions[i].y
+ return
+ control_positions: ->
+ ret = []
+ for n in @nodes
+ ret.push x: @x + n.x, y: @y + n.y
+ return ret
+ make_controls: (args) -> # create controls, return them
+ console.log 'make line controls'
+ if @controls.length > 0
+ if console?.log?
+ console.log "warning: re-adding controls"
+ @kill_controls()
+ positions = @control_positions()
+ for i in [0...positions.length]
+ @controls.push new ControlPath {
+ svg: @svg
+ x: positions[i].x
+ y: positions[i].y
+ done: args.done
+ drag: @node_dragger i
+ shape: shape_node_move
+ }
+ return @controls
+