JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
boxes don't click/hover as if they're filled
[crayon_mockup.git] / main.coffee
1 # Copyright 2015 Jason Woofenden
2 #
3 # This program is free software: you can redistribute it and/or modify it under
4 # the terms of the GNU General Public License as published by the Free Software
5 # Foundation, either version 3 of the License, or (at your option) any later
6 # version.
7 #
8 # This program is distributed in the hope that it will be useful, but WITHOUT
9 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 # FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
11 # details.
12 #
13 # You should have received a copy of the GNU General Public License along with
14 # this program.  If not, see <http://www.gnu.org/licenses/>.
15
16
17 # settings
18 width = 800
19 height = 600
20 supply_height = 96
21 CLICK_FUZ = 10 # this far away from things is close enough to be "clicked on"
22 PROX_MAX = CLICK_FUZ * CLICK_FUZ
23 PROX_TOO_FAR = PROX_MAX + 1 # no need to be precice when it's too far
24
25 # constants
26 STATES = {
27         NORMAL:   { txt: 'normal' }
28         SELECTED: { txt: 'selected' }
29         DRAGGING: { txt: 'dragging' }
30         EDITING:  { txt: 'editing' }
31 }
32 TYPE_WIDGET = 1
33 TYPE_CONTROL = 2
34
35 # json (compiled to javascript and minified) is ~8% smaller than the resulting xml
36 json_to_svg = (json) ->
37         for tag, attrs of json
38                 el = document.createElementNS 'http://www.w3.org/2000/svg', tag
39                 for k, v of attrs
40                         if k is 'children'
41                                 for child in v
42                                         el.appendChild json_to_svg child
43                         else if k is 'contents'
44                                 el.appendChild document.createTextNode v
45                         else
46                                 el.setAttribute k, v
47         return el
48
49 resizer_nw = (widget) ->
50         return (dxy) ->
51                 widget.resize w: widget.width - dxy.x, h: widget.height - dxy.y
52                 widget.move x: widget.x + dxy.x, y: widget.y + dxy.y
53 resizer_n = (widget) ->
54         return (dxy) ->
55                 widget.resize w: widget.width, h: widget.height - dxy.y
56                 widget.move x: widget.x, y: widget.y + dxy.y
57 resizer_ne = (widget) ->
58         return (dxy) ->
59                 widget.resize w: widget.width + dxy.x, h: widget.height - dxy.y
60                 widget.move x: widget.x, y: widget.y + dxy.y
61 resizer_e = (widget) ->
62         return (dxy) ->
63                 widget.resize w: widget.width + dxy.x, h: widget.height
64 resizer_se = (widget) ->
65         return (dxy) ->
66                 widget.resize w: widget.width + dxy.x, h: widget.height + dxy.y
67 resizer_s = (widget) ->
68         return (dxy) ->
69                 widget.resize w: widget.width, h: widget.height + dxy.y
70 resizer_sw = (widget) ->
71         return (dxy) ->
72                 widget.resize w: widget.width - dxy.x, h: widget.height + dxy.y
73                 widget.move x: widget.x + dxy.x, y: widget.y
74 resizer_w = (widget) ->
75         return (dxy) ->
76                 widget.resize w: widget.width - dxy.x, h: widget.height
77                 widget.move x: widget.x + dxy.x, y: widget.y
78 resizers = [
79         resizer_nw
80         resizer_n
81         resizer_ne
82         resizer_e
83         resizer_se
84         resizer_s
85         resizer_sw
86         resizer_w
87 ]
88 resizer_shapes = [
89         -> return "M#{@x - 5} #{@y - 5}h6l-2 2 4 4 2 -2v6h-6l2-2-4-4-2 2z"
90         -> return "M #{@x},#{@y - 7} l 4,4 -2.5,0 0,5 2.5,0 -4,4 -4,-4 2.5,0 0,-5 -2.5,0 z"
91         -> return "M#{@x + 5} #{@y - 5}v6l-2-2-4 4 2 2h-6v-6l2 2 4-4-2-2z"
92         -> return "M #{@x - 7},#{@y} l 4,-4 0,2.5 5,0 0,-2.5 4,4 -4,4 0,-2.5 -5,0 0,2.5 z"
93 ]
94 shape_node_move = -> "M#{@x} #{@y - 9}l-2.5 4.5h2v2.404a2.156 2.156 0 0 0-1.596 1.596h-2.404v-2l-4.5 2.5 4.5 2.5v-2h2.404a2.156 2.156 0 0 0 1.596 1.596v2.404h-2l2.5 4.5 2.5-4.5h-2v-2.404a2.156 2.156 0 0 0 1.596-1.596h2.404v2l4.5-2.5-4.5-2.5v2h-2.404a2.156 2.156 0 0 0-1.596-1.596v-2.404h2l-2.5-4.5z"
95
96 next_widget_id = 0
97 # public vars: x, y, width, height, el
98 class Visible
99         # required args: svg
100         constructor: (args) ->
101                 @id = next_widget_id
102                 next_widget_id += 1
103                 @svg = args.svg
104                 @x = args.x ? 1
105                 @y = args.y ? 1
106                 @width = args.width ? 50
107                 @height = args.height ? 34
108                 @state = args.state ? STATES.NORMAL
109                 @hover = false
110         destruct: ->
111         update_class: ->
112                 css_class = "#{@css_class} #{@state.txt}"
113                 if @hover
114                         css_class += " hover"
115                 @el.setAttribute 'class', css_class
116         set_hover: (tf) ->
117                 if tf != @hover
118                         @hover = tf
119                         @update_class()
120         move: (xy) -> # just move
121                 @x = xy.x
122                 @y = xy.y
123         drag: (dxy) -> # react to mouse drag (obey constraints, etc.)
124                 @move x: @x + dxy.x, y: @y + dxy.y
125         proximity: (xy) -> # return the square of the distance to your visible bits
126                 return PROX_TOO_FAR
127         set_state: (state) ->
128                 @state = state
129
130 class Control extends Visible
131         constructor: (args) ->
132                 super args
133                 @type = TYPE_CONTROL
134                 @on_drag = args.drag
135                 @on_destruct = args.done ? null
136         destruct: ->
137                 super()
138                 if @on_destruct?
139                         @on_destruct @
140         drag: (args) -> # call this when control point is being manipulated directly
141                 @on_drag args
142         proximity: (xy) -> # return the square of the distance to your visible bits
143                 dx = xy.x - @x
144                 dy = xy.y - @y
145                 return dx * dx + dy * dy
146 class ControlPath extends Control
147         constructor: (args) ->
148                 super args
149                 @css_class = 'control_point'
150                 @make_path = args.shape
151                 @el = json_to_svg path:
152                         d: @make_path()
153                         class: 'control_point normal'
154                 @svg.appendChild @el
155         destruct: ->
156                 super()
157                 if @el?
158                         @svg.removeChild @el
159         move: (args) ->
160                 super args
161                 @el.setAttribute 'd', @make_path()
162
163 class Widget extends Visible
164         #sub-classes are expected to implement all of these:
165         constructor: (args) ->
166                 super args
167                 @controls = []
168                 @type = TYPE_WIDGET
169         destruct: ->
170                 @kill_controls()
171         clone: ->
172                 return new Widget @
173         make_controls: -> # create controls, return them
174                 return []
175         kill_controls: ->
176                 for c in @controls
177                         c.destruct()
178                 @controls = []
179                 return
180         move: (xy) -> # just move
181                 dx = xy.x - @x
182                 dy = xy.y - @y
183                 super xy
184                 for c in @controls
185                         c.move x: c.x + dx, y: c.y + dy
186         set_state: (state) ->
187                 return if @state is state
188                 if @state is STATES.EDITING
189                         @kill_controls()
190                 super state
191
192 class RectWidget extends Widget
193         constructor: (args) ->
194                 super args
195                 @css_class = 'box'
196                 @el = json_to_svg rect:
197                         x: @x + 1
198                         y: @y + 1
199                         width: @width - 2
200                         height: @height - 2
201                         class: 'box normal'
202                 @svg.appendChild @el
203         destruct: ->
204                 super()
205                 if @el?
206                         @svg.removeChild @el
207         clone: ->
208                 return new RectWidget @
209         set_state: (state) ->
210                 super state
211                 @update_class()
212         move: (args) ->
213                 super args
214                 @el.setAttribute 'x', @x + 1
215                 @el.setAttribute 'y', @y + 1
216                 @reposition_controls()
217         proximity: (xy) -> # return the square of the distance to your visible bits
218                 x = xy.x
219                 y = xy.y
220                 prox = PROX_TOO_FAR
221                 in_x = false
222                 in_y = false
223                 if x > @x - CLICK_FUZ and x < @x + @width + CLICK_FUZ
224                         in_x = true
225                         if y < @y + @height / 2
226                                 new_prox = @y - y
227                         else
228                                 new_prox = @y + @height - y
229                         new_prox *= new_prox
230                         if new_prox < prox
231                                 prox = new_prox
232                 if y > @y - CLICK_FUZ and y < @y + @height + CLICK_FUZ
233                         in_y = true
234                         if x < @x + @width / 2
235                                 new_prox = @x - x
236                         else
237                                 new_prox = @x + @width - x
238                         new_prox *= new_prox
239                         if new_prox < prox
240                                 prox = new_prox
241                 # "hit" anything inside
242                 #if in_x and in_y and prox > PROX_MAX
243                 #       prox = PROX_MAX - 1
244                 return prox
245         resize: (wh) ->
246                 dw = wh.w - @width
247                 dh = wh.h - @height
248                 @width = wh.w
249                 @el.setAttribute 'width', @width - 2
250                 @height = wh.h
251                 @el.setAttribute 'height', @height - 2
252                 @reposition_controls()
253         reposition_controls: ->
254                 if @controls.length > 1
255                         positions = @control_positions()
256                         for i in [0...positions.length]
257                                 @controls[i].move x: positions[i].x, y: positions[i].y
258         control_positions: ->
259                 gap = 7
260                 mgap = 9
261                 w2p = Math.floor(@width / 2) + 0.5
262                 h2p = Math.floor(@height / 2) + 0.5
263                 return [
264                         { x: @x - gap, y: @y - gap }
265                         { x: @x + w2p, y: @y - mgap }
266                         { x: @x + @width + gap, y: @y - gap }
267                         { x: @x + @width + mgap, y: @y + h2p }
268                         { x: @x + @width + gap, y: @y + @height + gap }
269                         { x: @x + w2p, y: @y + @height + mgap }
270                         { x: @x - gap, y: @y + @height + gap }
271                         { x: @x - mgap, y: @y + h2p }
272                 ]
273         make_controls: (args) -> # create controls, return them
274                 if @controls.length > 0
275                         if console?.log?
276                                 console.log "warning: re-adding controls"
277                         @kill_controls()
278                 positions = @control_positions()
279                 for i in [0...positions.length]
280                         @controls.push new ControlPath {
281                                 svg: @svg
282                                 x: positions[i].x
283                                 y: positions[i].y
284                                 done: args.done
285                                 drag: resizers[i] @
286                                 shape: resizer_shapes[i % resizer_shapes.length]
287                         }
288                 return @controls
289
290 class PolylineWidget extends Widget
291         constructor: (args) ->
292                 super args
293                 @css_class = 'polyline'
294                 @nodes = []
295                 for n in args.nodes
296                         @nodes.push x: n.x, y: n.y
297                 @el = json_to_svg path:
298                         d: @my_path_d()
299                         class: 'polyline normal'
300                 @svg.appendChild @el
301         destruct: ->
302                 super()
303                 if @el?
304                         @svg.removeChild @el
305         clone: ->
306                 return new PolylineWidget @
307         my_path_d: ->
308                 ret = ''
309                 for n in @nodes
310                         if ret is ''
311                                 ret += 'M'
312                         else
313                                 ret += 'L'
314                         ret += n.x + @x
315                         ret += ' '
316                         ret += n.y + @y
317                 return ret
318         set_state: (state) ->
319                 super state
320                 @update_class()
321         move: (args) ->
322                 super args
323                 @el.setAttribute 'd', @my_path_d()
324                 @reposition_controls()
325         proximity: (xy) -> # return the square of the distance to your visible bits
326                 prox = PROX_TOO_FAR
327                 for n, i in @nodes
328                         dx = @x + n.x - xy.x
329                         dy = @y + n.y - xy.y
330                         p = dx * dx + dy * dy
331                         if p < prox
332                                 prox = p
333                         if i > 0
334                                 l1x = @x + @nodes[i-1].x
335                                 l1y = @y + @nodes[i-1].y
336                                 l2x = @x + @nodes[i].x
337                                 l2y = @y + @nodes[i].y
338                                 ldx = l2x - l1x
339                                 ldy = l2y - l1y
340                                 if ldx is 0 # vertical line
341                                         if (xy.y < l1y) is (xy.y < l2y)
342                                                 continue
343                                         dx = l1x - xy.x
344                                         p = dx * dx
345                                 else if ldy is 0 # horizontal line
346                                         if (xy.x < l1x) is (xy.x < l2x)
347                                                 continue
348                                         dy = l1y - xy.y
349                                         p = dy * dy
350                                 else # slanty line
351                                         # https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
352                                         a = ldy
353                                         b = -1 * ldx
354                                         c = l2x * l1y - l2y * l1x
355                                         y_on_line = (a * (a * xy.y - b * xy.x) - b * c) / (a * a + b * b)
356                                         if (y_on_line < l1y) is (y_on_line < l2y)
357                                                 continue
358                                         p = (a * xy.x + b * xy.y + c) / Math.sqrt(a * a + b * b)
359                                         p *= p
360
361                                 if p < prox
362                                         prox = p
363                 return prox
364         resize: (wh) ->
365                 # FIXME (apply to more than just 2nd node)
366                 @nodes[1].x = wh.w
367                 @nodes[1].y = wh.h
368                 @width = wh.w
369                 @height = wh.h
370                 @el.setAttribute 'd', @my_path_d()
371                 @reposition_controls()
372                 return
373         node_dragger: (i) ->
374                 if i is 0
375                         return (dxy) =>
376                                 for i in [1...@nodes.length]
377                                         @nodes[i].x -= dxy.x
378                                         @nodes[i].y -= dxy.y
379                                 @move x: @x + dxy.x, y: @y + dxy.y
380                 return (dxy) =>
381                         @nodes[i].x += dxy.x
382                         @nodes[i].y += dxy.y
383                         @el.setAttribute 'd', @my_path_d()
384                         @reposition_controls()
385         reposition_controls: ->
386                 if @controls.length > 1
387                         positions = @control_positions()
388                         for i in [0...positions.length]
389                                 @controls[i].move x: positions[i].x, y: positions[i].y
390                 return
391         control_positions: ->
392                 ret = []
393                 for n in @nodes
394                         ret.push x: @x + n.x, y: @y + n.y
395                 return ret
396         make_controls: (args) -> # create controls, return them
397                 console.log 'make line controls'
398                 if @controls.length > 0
399                         if console?.log?
400                                 console.log "warning: re-adding controls"
401                         @kill_controls()
402                 positions = @control_positions()
403                 for i in [0...positions.length]
404                         @controls.push new ControlPath {
405                                 svg: @svg
406                                 x: positions[i].x
407                                 y: positions[i].y
408                                 done: args.done
409                                 drag: @node_dragger i
410                                 shape: shape_node_move
411                         }
412                 return @controls
413
414 # called automatically on domcontentloaded
415 init = ->
416         svg_offset = null
417         $container = $ '.crayon_mockup'
418         svg = json_to_svg svg: width: width, height: height, viewBox: "0 0 #{width} #{height}"
419         $svg = $ svg
420         $container.append $svg
421         svg.appendChild json_to_svg filter:
422                 id: 'crayon', filterUnits: 'userSpaceOnUse'
423                 x: '-5%', y: '-5%', height: '110%', width: '110%'
424                 children: [
425                         { feTurbulence: baseFrequency: '.3', numOctaves: '2', type: 'fractalNoise' }
426                         { feDisplacementMap: scale: '6', xChannelSelector: 'R', in: 'SourceGraphic' }
427                 ]
428         svg.appendChild json_to_svg style:
429                 type: 'text/css'
430                 contents: '.box.normal,.polyline.normal{filter: url(#crayon)}'
431
432         # create canvas border
433         svg.appendChild json_to_svg rect:
434                 x: 1
435                 y: supply_height + 1
436                 width: width - 2
437                 height: height - 2 - supply_height
438                 class: 'canvas_border'
439
440         supply = {}
441         supply_count = 0
442         supply_add = (type, args) ->
443                 args.x ?= 0
444                 args.y ?= 0
445                 args.x += 30 + supply_count * 90
446                 args.y += (supply_height - 50) / 2
447                 args.svg = svg
448                 w = new type args
449                 supply[w.id] = w
450                 supply_count += 1
451         supply_add RectWidget, width: 50, height: 50
452         supply_add PolylineWidget, y: 25, nodes: [{x: 0, y: 0}, {x: 50, y: 0}]
453         supply_add PolylineWidget, x: 25, nodes: [{x: 0, y: 0}, {x: 0, y: 50}]
454         supply_add PolylineWidget, x: 10, nodes: [{x: 0, y: 0}, {x: 15, y: 50}, {x: 30, y: 0}]
455         supply_add PolylineWidget, nodes: [{x: 0, y: 50}, {x: 17, y: 0}, {x: 33, y: 50}, {x: 50, y: 0}]
456
457         # editor state
458         controls_layer = { all: {}, selected: {} }
459         widget_layer = { all: {}, selected: {}, editing: null }
460         layers = [controls_layer, widget_layer]
461         hovered = null # can be in any layer
462         dragging = false # mouse state
463         drag_layer = null
464         drag_from = x: 0, y: 0 # mouse was here at last frame of drag
465         shift_key_down = false
466
467         stop_editing = ->
468                 if widget_layer.editing
469                         widget_layer.editing.kill_controls()
470                         widget_layer.editing = null
471         deselect = (layer, s) ->
472                 return unless layer.selected[s.id]?
473                 s.set_state STATES.NORMAL
474                 delete layer.selected[s.id]
475                 if widget_layer.editing is s
476                         widget_layer.editing = null
477                 return
478         deselect_all = (layer, except = null) ->
479                 for id, s of layer.selected
480                         deselect layer, s
481                 return
482         _select = (layer, s) -> # don't call this directly, use select_only() or select_also()
483                 s.set_state STATES.SELECTED
484                 layer.selected[s.id] = s
485                 return
486         select_only = (layer, s) ->
487                 deselect_all layer, s
488                 return if layer.selected[s.id]?
489                 _select layer, s
490                 return
491         select_also = (layer, s) ->
492                 return if layer.selected[s.id]?
493                 if layer is widget_layer
494                         stop_editing()
495                 _select layer, s
496                 return
497         find_closest = (widgets, xy) ->
498                 prox = PROX_TOO_FAR
499                 closest = null
500                 for id, w of widgets
501                         new_prox = w.proximity xy
502                         if new_prox < prox
503                                 prox = new_prox
504                                 closest = w
505                 if prox > PROX_MAX
506                         return null
507                 return closest
508         svg_event_to_xy = (e) ->
509                 unless svg_offset?
510                         svg_offset = $svg.offset()
511                 return {
512                         x: Math.round(e.pageX - svg_offset.left)
513                         y: Math.round(e.pageY - svg_offset.top)
514                 }
515         closest_in_layers = (xy) ->
516                 for layer in layers
517                         s = find_closest layer.selected, xy
518                         return layer: layer, s: s if s?
519                         s = find_closest layer.all, xy
520                         return layer: layer, s: s if s?
521                 return null
522         mousedown = (e) ->
523                 hit = null
524                 closest = null
525                 layer = null
526                 mousemove e
527                 if dragging # two mousedowns in a row?! it happens
528                         return mouseup e
529                 xy = svg_event_to_xy e
530                 if xy.y < supply_height
531                         s = find_closest supply, xy
532                         if s?
533                                 hit = {
534                                         s: s.clone()
535                                         layer: widget_layer
536                                 }
537                                 widget_layer.all[hit.s.id] = hit.s
538                 else
539                         hit = closest_in_layers xy
540                 if hit?
541                         if hit.layer.selected[hit.s.id]
542                                 # already selected
543                                 # TODO start detection of a click that doesn't drag (to shrink selection)
544                         else if xy.y < supply_height
545                                 # dragging a new thing in
546                                 select_only hit.layer, hit.s
547                         else if shift_key_down
548                                 select_also hit.layer, hit.s
549                         else
550                                 select_only hit.layer, hit.s
551                         for id, s of hit.layer.selected
552                                 s.set_state STATES.DRAGGING
553                         dragging = true
554                         drag_layer = hit.layer
555                         drag_from = xy
556                 else
557                         deselect_all widget_layer
558                 return
559         mouseup = (e) ->
560                 mousemove e
561                 if dragging
562                         selected_count = 0
563                         for id, s of drag_layer.selected
564                                 if s.y < supply_height and drag_layer is widget_layer
565                                         deselect drag_layer, s
566                                         s.destruct()
567                                         delete drag_layer.all[id]
568                                 else
569                                         selected_count += 1
570                                         s.set_state STATES.SELECTED
571                         if drag_layer is widget_layer and selected_count is 1
572                                 for id, s of drag_layer.selected
573                                         s.set_state STATES.EDITING
574                                         cs = s.make_controls done: (c) ->
575                                                 deselect controls_layer, c
576                                                 delete controls_layer.all[c.id]
577                                         for c in cs
578                                                 controls_layer.all[c.id] = c
579                                         widget_layer.editing = s
580                 dragging = false
581                 return
582         mousemove = (e) ->
583                 xy = svg_event_to_xy e
584                 if dragging
585                         return if drag_from.x is xy.x and drag_from.y is xy.y
586                         rel_x = xy.x - drag_from.x
587                         rel_y = xy.y - drag_from.y
588                         drag_from = xy
589                         for id, w of drag_layer.selected
590                                 w.drag x: rel_x, y: rel_y
591                 else
592                         hit = closest_in_layers xy
593                         if hovered and hovered isnt hit?.s
594                                 hovered.set_hover false
595                         return unless hit?
596                         hovered = hit.s
597                         hovered.set_hover true
598                 return
599         $svg.mousedown (e) ->
600                 mousedown e
601                 return false
602         $svg.mouseup (e) ->
603                 mouseup e
604                 return false
605         $svg.mousemove (e) ->
606                 mousemove e
607                 return false
608         $(document).on 'keyup keydown', (e) ->
609                 shift_key_down = e.shiftKey
610                 return true
611         #($ document).keydown (e) ->
612
613 $ init