-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlivegraph.coffee
858 lines (659 loc) · 21.5 KB
/
livegraph.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# Real-time canvas plotting library
# Distributed under the terms of the BSD License
# (C) 2011 Kevin Mehall (Nonolith Labs) <[email protected]>
livegraph = window.livegraph = {}
PADDING = livegraph.PADDING = 10
AXIS_SPACING = livegraph.AXIS_SPACING = 25
class livegraph.Axis
constructor: (@min, @max, @unit='', @scaleUnit=false) ->
if @max == 'auto'
@autoScroll = min
@max = 0
else
@autoscroll = false
@visibleMin = @min
@visibleMax = @max
@isAnimating = false
span: -> @visibleMax - @visibleMin
xtransform: (x, geom) ->
(x - @visibleMin) * geom.width / @span() + geom.xleft
ytransform: (y, geom) ->
geom.ybottom - (y - @visibleMin) * geom.height / @span()
invYtransform: (ypx, geom) ->
(geom.ybottom - ypx)/geom.height * @span() + @visibleMin
window: (min, max, done, target) ->
if min != @visibleMin or max != @visibleMax
@visibleMin = min
@visibleMax = max
@isAnimating = true
@windowChanged(min, max, done, target)
if done and @isAnimating
@windowDoneAnimating(@visibleMin, @visibleMax)
@isAnimating = false
windowChanged: (min, max, done) ->
windowDoneAnimating: (min, max) ->
gridLabels: (ticks) ->
unitlib.gridLabels(@visibleMin, @visibleMax,
@unit, ticks, @scaleUnit,
@min, @max, @prescale)
# Logarithmic axis.
# Important Note: this only adjusts the axis labels. The corresponding
# values in the series, and window/range parameters are expected to
# be already log-transformed.
class livegraph.LogAxis extends livegraph.Axis
gridLabels: (ticks) ->
unitlib.logGridLabels(@visibleMin, @visibleMax, @unit)
class DigitalAxis
min = 0
max = 1
grid: -> [0, 1]
xtransform: (x, geom) -> if x then geom.xleft else geom.xright
ytransform: (y, geom) -> if y then geom.ytop else geom.ybottom
invYtransform: (ypx, geom) -> (geom.ybottom - ypx) > geom.height/2
livegraph.digitalAxis = new DigitalAxis()
class livegraph.Series
constructor: (@xdata, @ydata, @color, @style) ->
cssColor: -> "rgb(#{@color[0]},#{@color[1]},#{@color[2]})"
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
(callback, element) -> window.setTimeout(callback, 1000/60)
# Creates a matrix A = sx 0 dx
# 0 sy dy
# 0 0 1
# based off of the geometry (view) and axis settings such that
# A * vector(x, y, 1) in unit space = the point in pixel space
# or, alternatively, x'=x*sx+dx; y'=y*sy+dy
makeTransform = livegraph.makeTransform = (geom, xaxis, yaxis, w, h) ->
sx = geom.width / xaxis.span()
sy = -geom.height / yaxis.span()
dx = geom.xleft - xaxis.visibleMin*sx
dy = geom.ybottom - yaxis.visibleMin*sy
return [sx, sy, dx, dy]
# Apply a transformation generated by makeTransform to a point
transform = livegraph.transform = (x, y, [sx, sy, dx, dy]) ->
return [dx + x*sx, dy+y*sy]
# Use a transformation from makeTransform to go from pixel to unit space
invTransform = livegraph.invTransform = (x, y, [sx, sy, dx, dy]) ->
return [(x-dx)/sx, (y-dy)/sy]
# Snap a pixel coordinate to a position that will create a sharp line
snapPx = (px) -> Math.round(px - 0.5) + 0.5
relMousePos = (elem, event) ->
o = $(elem).offset()
return [event.pageX-o.left, event.pageY-o.top]
class livegraph.canvas
constructor: (@div, @xaxis, @yaxis, @series, opts={}) ->
@div.setAttribute('class', 'livegraph')
@axisCanvas = document.createElement('canvas')
@graphCanvas = document.createElement('canvas')
@div.appendChild(@axisCanvas)
@div.appendChild(@graphCanvas)
$(@div).mousedown(@mousedown)
$(@div).dblclick(@doubleclick)
$(@div).bind('contextmenu', -> false)
@showYleft = opts.yleft ? true
@showYright = opts.yright ? true
@showYgrid = opts.ygrid ? true
@showXbottom = opts.xbottom ? false
@showXgrid = opts.xgrid ? false
@showXgridZero = opts.xgridZero ? false
@gridcolor = opts.gridcolor ? 'rgba(0,0,0,0.08)'
@rightClickTime = 0
@overlays = []
@action = false
@ctxa = @axisCanvas.getContext('2d')
if (window.nowebgl or not @init_webgl()) then @init_canvas2d()
#@needsRedraw()
init_canvas2d: ->
@ctxg = @graphCanvas.getContext('2d')
@redrawGraph = @redrawGraph_canvas2d
@refreshViewParams = -> false
@renderer = 'canvas2d'
return true
init_webgl: ->
shader_vs = """
attribute float x;
attribute float y;
uniform mat4 transform;
void main(void) {
gl_Position = transform * vec4(x, y, 1.0, 1.0);
gl_Position.z = -1.0;
gl_Position.w = 1.0;
}
"""
shader_fs = """
#ifdef GL_ES
precision mediump float;
#endif
uniform vec4 color;
void main(void) {
gl_FragColor = color;
}
"""
@gl = gl = @graphCanvas.getContext("experimental-webgl")
if not @gl then return false
compile_shader = (type, source) ->
s = gl.createShader(type)
gl.shaderSource(s, source)
gl.compileShader(s)
if !gl.getShaderParameter(s, gl.COMPILE_STATUS)
console.error(gl.getShaderInfoLog(s))
return null
return s
fs = compile_shader(gl.FRAGMENT_SHADER, shader_fs)
vs = compile_shader(gl.VERTEX_SHADER, shader_vs)
if not fs and vs then return false
gl.shaderProgram = gl.createProgram()
gl.attachShader(gl.shaderProgram, fs)
gl.attachShader(gl.shaderProgram, vs)
gl.linkProgram(gl.shaderProgram)
if (!gl.getProgramParameter(gl.shaderProgram, gl.LINK_STATUS))
console.error "Could not initialize shaders"
return false
gl.useProgram(gl.shaderProgram)
gl.shaderProgram.attrib =
x: gl.getAttribLocation(gl.shaderProgram, "x")
y: gl.getAttribLocation(gl.shaderProgram, "y")
gl.shaderProgram.uniform =
transform: gl.getUniformLocation(gl.shaderProgram, "transform")
color: gl.getUniformLocation(gl.shaderProgram, "color")
gl.enableVertexAttribArray(gl.shaderProgram.attrib.x)
gl.enableVertexAttribArray(gl.shaderProgram.attrib.y)
gl.enable(gl.GL_LINE_SMOOTH)
gl.hint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
gl.enable(gl.GL_BLEND)
gl.blendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
gl.xBuffer = gl.createBuffer()
gl.yBuffer = gl.createBuffer()
@renderer = 'webgl'
@redrawGraph = @redrawGraph_webgl
@refreshViewParams = @webgl_refreshViewParams
return true
perfStat_enable: (div)->
@psDiv = div
@psCount = 0
@psSum = 0
@psRunningSum = 0
@psRunningCount = 0
setInterval((=>
@psRunningSum += @psSum
@psRunningCount += @psCount
@psDiv.innerHTML = "#{@renderer}: #{@psCount}fps; #{@psSum}ms draw time; Avg: #{@psRunningSum/@psRunningCount}"
@psCount = 0
@psSum = 0
), 1000)
perfStat: (time) ->
@psCount += 1
@psSum += time
startAction: (action) ->
if @action
@action.cancel()
@action = action
mousedown: (e) =>
if e.button == 0
pos = origPos = relMousePos(@div, e)
@onClick(pos, e)
else if e.button == 2
# Simulate right-double-click
t = +new Date()
if @rightClickTime and @rightClickTime + 200 > t
@rightClickTime = 0
@onDblClick(e, relMousePos(@div, e), 2)
else
@rightClickTime = t
return
startDrag: (origPos) ->
pos = origPos
mousemove = (e) =>
pos = relMousePos(@div, e)
if @action then @action.onDrag(pos, origPos)
return
mouseup = =>
if @action then @action.onRelease(pos, origPos)
$(window).unbind('mousemove', mousemove)
.unbind('mouseup', mouseup)
.css('cursor', 'auto')
return
$(window).mousemove(mousemove)
.mouseup(mouseup)
return mouseup
onClick: (pos) -> false
doubleclick: (e) =>
pos = relMousePos(@div, e)
@onDblClick(e, pos, 1)
onDblClick: (e, pos, btn) ->
resized: () ->
unless @div.offsetWidth > 0 and @div.offsetHeight > 0 and @xaxis and @yaxis
return
@width = @div.offsetWidth
@height = @div.offsetHeight
@axisCanvas.width = @width
@axisCanvas.height = @height
@graphCanvas.width = @width
@graphCanvas.height = @height
@geom =
ytop: PADDING
ybottom: @height - (PADDING + @showXbottom * AXIS_SPACING)
xleft: PADDING + @showYleft * AXIS_SPACING
xright: @width - (PADDING + @showYright * AXIS_SPACING)
width: @width - 2*PADDING - (@showYleft+@showYright) * AXIS_SPACING
height: @height - 2*PADDING - @showXbottom * AXIS_SPACING
@xgridticks = Math.min(@width/50, 10)
@ygridticks = @height/35
if @onResized
@onResized()
@refreshViewParams()
@needsRedraw(true)
return
redrawAxis: ->
@ctxa.clearRect(0,0,@width, @height)
if @showXgrid or @showXbottom
xgrid = @xaxis.gridLabels(@xgridticks)
if @showYgrid or @showYleft or @showYright
ygrid = @yaxis.gridLabels(@ygridticks)
if @showXgrid or @showXgridZero then @drawXgrid(xgrid)
if @showXbottom then @drawXAxis(xgrid, @geom.ybottom)
if @showYgrid then @drawYgrid(ygrid)
if @showYleft then @drawYAxis(ygrid, @geom.xleft, 'right', -5)
if @showYright then @drawYAxis(ygrid, @geom.xright, 'left', 8)
drawXAxis: (xgrid, y) ->
@ctxa.strokeStyle = 'black'
@ctxa.lineWidth = 1
@ctxa.beginPath()
@ctxa.moveTo(snapPx(@geom.xleft), snapPx(y))
@ctxa.lineTo(snapPx(@geom.xright), snapPx(y))
@ctxa.stroke()
textoffset = 5
@ctxa.textAlign = 'center'
@ctxa.textBaseline = 'top'
for [x, label] in xgrid
@ctxa.beginPath()
xp = snapPx(@xaxis.xtransform(x, @geom))
@ctxa.moveTo(xp,y-4)
@ctxa.lineTo(xp,y+4)
@ctxa.stroke()
@ctxa.fillText(label, xp ,y+textoffset)
drawXgrid: (grid) ->
if @showXgridZero and not @showXgrid
grid = [0, '0']
@ctxa.strokeStyle = @gridcolor
@ctxa.lineWidth = 1
for [x, label] in grid
xp = snapPx(@xaxis.xtransform(x, @geom))
if xp > @geom.xright+1 or xp < @geom.xleft then continue
@ctxa.beginPath()
@ctxa.moveTo(xp, @geom.ybottom)
@ctxa.lineTo(xp, @geom.ytop)
@ctxa.stroke()
drawYAxis: (grid, x, align, textoffset) =>
@ctxa.strokeStyle = 'black'
@ctxa.lineWidth = 1
@ctxa.textAlign = align
@ctxa.textBaseline = 'middle'
@ctxa.beginPath()
@ctxa.moveTo(snapPx(x), snapPx(@geom.ytop))
@ctxa.lineTo(snapPx(x), snapPx(@geom.ybottom))
@ctxa.stroke()
for [y, label] in grid
yp = snapPx(@yaxis.ytransform(y, @geom))
#draw side axis ticks and labels
@ctxa.beginPath()
@ctxa.moveTo(x-4, yp)
@ctxa.lineTo(x+4, yp)
@ctxa.stroke()
@ctxa.fillText(label, x+textoffset, yp)
drawYgrid: (grid) ->
@ctxa.strokeStyle = @gridcolor
@ctxa.lineWidth = 1
for [y, label] in grid
yp = snapPx(@yaxis.ytransform(y, @geom))
@ctxa.beginPath()
@ctxa.moveTo(@geom.xleft, yp)
@ctxa.lineTo(@geom.xright, yp)
@ctxa.stroke()
needsRedraw: (fullRedraw=false) ->
@axisRedrawRequested ||= fullRedraw
if not @redrawRequested
@redrawRequested = true
requestAnimFrame(@redraw, @graphCanvas)
redraw: =>
startTime = new Date()
if @height != @div.offsetHeight or @width != @div.offsetWidth
@resized()
@redrawRequested = false
if @action
@action.onAnim()
if @axisRedrawRequested
@redrawAxis()
@refreshViewParams()
@axisRedrawRequested = false
for overlay in @overlays
overlay.resized()
@redrawGraph()
@perfStat(new Date()-startTime)
return
redrawGraph_canvas2d: ->
@ctxg.clearRect(0,0,@width, @height)
@ctxg.lineWidth = 2
[sx, sy, dx, dy] = makeTransform(@geom, @xaxis, @yaxis)
for series in @series
@ctxg.strokeStyle = series.cssColor()
@ctxg.save()
@ctxg.beginPath()
@ctxg.rect(@geom.xleft, @geom.ytop, @[email protected], @[email protected])
@ctxg.clip()
@ctxg.beginPath()
datalen = Math.min(series.xdata.length, series.ydata.length)
cull = true
for i in [0...datalen]
if cull and series.xdata[i+1] < @xaxis.visibleMin
continue
x = series.xdata[i]
y = series.ydata[i]
@ctxg.lineTo(x*sx + dx, y*sy+dy)
if cull and x > @xaxis.visibleMax
break
@ctxg.stroke()
@ctxg.restore()
webgl_refreshViewParams: ->
gl = @gl
gl.clearColor(0.0, 0.0, 0.0, 0.0)
gl.enable(gl.SCISSOR_TEST)
gl.viewport(0, 0, @width, @height)
gl.scissor(@geom.xleft, @[email protected], @geom.width, @geom.height)
gl.lineWidth(2)
[sx, sy, dx, dy] = makeTransform(@geom, @xaxis, @yaxis)
w = 2.0/@width
h = -2.0/@height
# column-major order!
tmatrix = [sx*w, 0, 0, 0, 0, sy*h, 0, 0, dx*w, dy*h, 0, 0, -1, 1, -1, 1]
gl.uniformMatrix4fv(gl.shaderProgram.uniform.transform, false, new Float32Array(tmatrix))
gl.uniform4fv(gl.shaderProgram.uniform.color, new Float32Array(
[@series[0].color[0]/255.0, @series[0].color[1]/255.0, @series[0].color[2]/255.0, 1]))
redrawGraph_webgl: ->
gl = @gl
gl.clear(gl.COLOR_BUFFER_BIT)
for series in @series
gl.bindBuffer(gl.ARRAY_BUFFER, gl.xBuffer)
gl.bufferData(gl.ARRAY_BUFFER, series.xdata, gl.STREAM_DRAW)
gl.vertexAttribPointer(gl.shaderProgram.attrib.x, 1, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, gl.yBuffer)
gl.bufferData(gl.ARRAY_BUFFER, series.ydata, gl.STREAM_DRAW)
gl.vertexAttribPointer(gl.shaderProgram.attrib.y, 1, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP, 0, series.xdata.length)
# Abstract base class for a UI overlay on top of the graph
class livegraph.Overlay
constructor: (lg) ->
@lg.overlays.push(this)
resized: ->
remove: ->
i = @lg.overlays.indexOf(this)
@lg.overlays.splice(i, 1)
class livegraph.Dot extends livegraph.Overlay
constructor: (@lg, @fill, @radius=5, @xpos='r') ->
@dot = document.createElement('canvas')
@dot.width = 2*@radius + 4
@dot.height = 2*@radius + 4
@center = @radius+2
@x = PADDING+AXIS_SPACING
@y = 0
$(@dot).css
position: 'absolute'
'margin-top':-@center
'margin-right':-@center
'margin-left':-@center
@ctx = @dot.getContext('2d')
$(@dot).appendTo(@lg.div)
super()
@render()
remove: ->
$(@dot).remove()
super()
resized: ->
@position(@x, @y)
position: (x, @y) ->
@x = x if x?
if not @lg.geom then return
# Hide if value is invalid
v = !isNaN(@y) and @y?
# Hide if off to the side
if not @xpos and @x > @lg.xaxis.visibleMax or @x < @lg.xaxis.visibleMin
v = false
# If visibility has changed, update it
v = if v then 'visible' else 'hidden'
if @dot.style.visibility != v then @dot.style.visibility=v
if @y > @lg.yaxis.visibleMax
@y = @lg.yaxis.visibleMax
shape = 'up'
else if y < @lg.yaxis.visibleMin
@y = @lg.yaxis.visibleMin
shape = 'down'
else
shape = 'circle'
# Find pixel position
[sx, sy, dx, dy] = makeTransform(@lg.geom, @lg.xaxis, @lg.yaxis)
@ty = ty = Math.round(dy+@y*sy)
# Bail out if it hasn't changed
#if not @lastY==@ty and not @xpos then return
#@lastY = @ty
if @shape != shape
@shape = shape
@render()
@dot.style.top = ty + 'px'
if @xpos is 'r'
@dot.style.right = @x + 'px'
@dot.style.left = "auto"
else if @xpos is 'l'
@dot.style.left = @x + 'px'
@dot.style.right = "auto"
else
@tx = tx = Math.round(dx + @x*sx)
@dot.style.left = tx + 'px'
@dot.style.right = "auto"
render: ->
@dot.width = @dot.width
@ctx.fillStyle = @fill
@ctx.strokeStyle = @fill
@ctx.lineWidth = 2
switch @shape
when 'circle'
@ctx.arc(@center, @center, @radius, 0, Math.PI*2, true);
when 'down'
@ctx.moveTo(@center, @center+@radius)
@ctx.lineTo(@center+@radius*0.86, @center-@radius*0.5)
@ctx.lineTo(@center-@radius*0.86, @center-@radius*0.5)
@ctx.lineTo(@center, @center+@radius)
when 'up'
@ctx.moveTo(@center, @center-@radius)
@ctx.lineTo(@center+@radius*0.86, @center+@radius*0.5)
@ctx.lineTo(@center-@radius*0.86, @center+@radius*0.5)
@ctx.lineTo(@center, @enter-@radius)
@ctx.fill()
@ctx.stroke()
isNear: (x, y, r) ->
return (Math.pow(x-@tx, 2) + Math.pow(y-@ty, 2)) < r*r
class livegraph.TriggerOverlay extends livegraph.Overlay
constructor: (@lg, color, border) ->
super()
@div = $('<div>')
@triangle = document.createElement('canvas')
@triangle.width = 10
@triangle.height = 11
@style(color, border)
@div.append(@triangle).appendTo(@lg.div)
style: (color='#ffaa00', border=1) ->
ctx = @triangle.getContext('2d')
ctx.clearRect(0, 0, @triangle.width, @triangle.height)
ctx.fillStyle = color
ctx.moveTo(0, 0)
ctx.lineTo(10, 5.5)
ctx.lineTo(0, 11)
ctx.lineTo(0,0)
ctx.fill()
$(@div).css
position: 'absolute'
left: PADDING + AXIS_SPACING
right: PADDING + AXIS_SPACING
'border-top': "#{border}px solid #{color}"
height: 0
$(@triangle).css
'margin-top':-6
'margin-left':-3
showBorder: (border) ->
$(@div).css
'border-top-width': if border then 1 else 0
remove: ->
$(@div).remove()
super()
resized: ->
@position(@y)
position: (@y) ->
if not @lg.geom then return
@y = Math.max(@lg.yaxis.visibleMin, Math.min(@lg.yaxis.visibleMax, @y))
# Find pixel position
[sx, sy, dx, dy] = makeTransform(@lg.geom, @lg.xaxis, @lg.yaxis)
ty = Math.round(dy+@y*sy)
@div.get(0).style.top = "#{ty}px"
# Abstract base for classes that manage user interactions with a Livegraph
# lg - The LiveGraph which started the interaction.
# Its properties will be used by default
# origPos - The original position of the user action
# allTargets - other LiveGraph instances that need to be updated
# because they share state - e.g. axes
class livegraph.Action
constructor: (@lg, @origPos, @allTargets=[@lg], @doneCallback) ->
@stop = false
for tgt in @allTargets
tgt.startAction()
@lg.startAction(this)
# Queue a redraw of all target graphs
redraw: (redrawAxes) ->
for graph in @allTargets
graph.needsRedraw(redrawAxes)
# Prevent further effects
# (subclasses should test this flag)
cancel: ->
@stop = true
if @doneCallback then @doneCallback()
@doneCallback = null
# Called when the mouse is dragged with the button still down
onDrag: ([x, y]) ->
# Called when the button is released
onRelease: ->
# Called on the redraw event
onAnim: ->
# Helper for the drag-to scroll behavior with momentum and rebound
class livegraph.DragScrollAction extends livegraph.Action
constructor: (lg, origPos, allTargets=null, doneCallback=null) ->
super(lg, origPos, allTargets, doneCallback)
@lg.startDrag(origPos)
# Save some original state
@origMin = @lg.xaxis.visibleMin
@origMax = @lg.xaxis.visibleMax
@span = @lg.xaxis.span()
# Conversion factor - pixels per graph unit
@scale = makeTransform(@lg.geom, @lg.xaxis, @lg.yaxis)[0]
@velocity = 0
@pressed = true
@x = @lastX = @origPos[0]
@t = +new Date()
onDrag: ([x, y]) ->
@scrollTo(x)
@x = x # Save position so onAnim can compute velocity
scrollTo: (x) ->
scrollby = (x-@origPos[0])/@scale
@lg.xaxis.window(@origMin - scrollby, @origMax - scrollby)
@redraw(true)
onRelease: ->
@pressed = false
@t = +new Date()-1
# force a redraw to get animation timer started
@redraw(true)
onAnim: ->
if @stop then return
t = +new Date()
dt = Math.min(t - @t, 100)
@t = t
if dt == 0 then return
minOvershoot = Math.max(@lg.xaxis.min - @lg.xaxis.visibleMin, 0)
maxOvershoot = Math.max(@lg.xaxis.visibleMax - @lg.xaxis.max, 0)
if @pressed
dx = @x - @lastX
@lastX = @x
@velocity = dx/dt
overshoot = Math.max(minOvershoot, maxOvershoot)
if overshoot > 0
@velocity *= (1-overshoot*@scale)/200
else
if minOvershoot*@scale > 1
if @velocity <= 0
@velocity = -1*minOvershoot*@scale/100
else
@velocity -= 0.1*dt
else if maxOvershoot*@scale > 1
if @velocity >= 0
@velocity = 1*maxOvershoot*@scale/100
else
@velocity += 0.1*dt
else
vstep = (if @velocity > 0 then 1 else -1) * 0.05
@velocity -= vstep
if (Math.abs(@velocity)) < Math.abs(vstep)*10
# Velocity has become negligible
# But if we're against min/max, stop exactly on it
if minOvershoot
@lg.xaxis.window(@lg.xaxis.min, @lg.xaxis.min + @span)
@redraw(true)
else if maxOvershoot
@lg.xaxis.window(@lg.xaxis.max - @span, @lg.xaxis.max)
@redraw(true)
@cancel()
return
@x = @x + @velocity*dt
@scrollTo(@x)
cancel: ->
@lg.xaxis.window(@lg.xaxis.visibleMin, @lg.xaxis.visibleMax, true)
super()
class livegraph.AnimateXAction extends livegraph.Action
constructor: (opts, lg, @endMin, @endMax, allTargets=null, doneCallback=null) ->
super(lg, null, allTargets, doneCallback)
@time = opts.time
@origMin = @lg.xaxis.visibleMin
@origMax = @lg.xaxis.visibleMax
tooMax = @endMax > @lg.xaxis.max
tooMin = @endMin < @lg.xaxis.min
if tooMin and tooMax
@endMax = @lg.xaxis.max
@endMin = @lg.xaxis.min
else if tooMax
@endMax = @lg.xaxis.max
@endMin = @endMax - @endSpan
else if tooMin
@endMin = @lg.xaxis.min
@endMax = @endMin + @endSpan
@startT = +new Date()
@redraw(true)
onAnim: ->
if @stop then return
t = +new Date() - @startT
ps = t / @time
pe = 1-ps
if ps > 1
@cancel()
else
@lg.xaxis.window(@origMin*pe + @endMin*ps, @origMax*pe + @endMax*ps, false, [@endMin, @endMax])
@redraw(true)
cancel: ->
# don't want to get stuck between zoom levels
@lg.xaxis.window(@endMin, @endMax, true)
@redraw(true)
super()
class livegraph.ZoomXAction extends livegraph.AnimateXAction
constructor: (opts, @lg, origPos, allTargets=null, doneCallback=null) ->
@startSpan = @lg.xaxis.span()
@endSpan = @startSpan * opts.zoomFactor
@center = invTransform(origPos[0], origPos[1], makeTransform(@lg.geom, @lg.xaxis, @lg.yaxis))[0]
super(opts, lg, @center - @endSpan/2, @center + @endSpan/2, allTargets, doneCallback)