-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.jsPlumb-1.7.2.js
11214 lines (9958 loc) · 456 KB
/
jquery.jsPlumb-1.7.2.js
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* jsBezier-0.6
*
* Copyright (c) 2010 - 2013 Simon Porritt ([email protected])
*
* licensed under the MIT license.
*
* a set of Bezier curve functions that deal with Beziers, used by jsPlumb, and perhaps useful for other people. These functions work with Bezier
* curves of arbitrary degree.
*
* - functions are all in the 'jsBezier' namespace.
*
* - all input points should be in the format {x:.., y:..}. all output points are in this format too.
*
* - all input curves should be in the format [ {x:.., y:..}, {x:.., y:..}, {x:.., y:..}, {x:.., y:..} ]
*
* - 'location' as used as an input here refers to a decimal in the range 0-1 inclusive, which indicates a point some proportion along the length
* of the curve. location as output has the same format and meaning.
*
*
* Function List:
* --------------
*
* distanceFromCurve(point, curve)
*
* Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier,
* so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values
* of the curve and the point - it will most likely be pixels.
*
* gradientAtPoint(curve, location)
*
* Calculates the gradient to the curve at the given location, as a decimal between 0 and 1 inclusive.
*
* gradientAtPointAlongCurveFrom (curve, location)
*
* Calculates the gradient at the point on the given curve that is 'distance' units from location.
*
* nearestPointOnCurve(point, curve)
*
* Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the
*point's coordinates and also the 'location' of the point (see above), for example: { point:{x:551,y:150}, location:0.263365 }.
*
* pointOnCurve(curve, location)
*
* Calculates the coordinates of the point on the given Bezier curve at the given location.
*
* pointAlongCurveFrom(curve, location, distance)
*
* Calculates the coordinates of the point on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
* space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
*
* locationAlongCurveFrom(curve, location, distance)
*
* Calculates the location on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
* space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
*
* perpendicularToCurveAt(curve, location, length, distance)
*
* Calculates the perpendicular to the given curve at the given location. length is the length of the line you wish for (it will be centered
* on the point at 'location'). distance is optional, and allows you to specify a point along the path from the given location as the center of
* the perpendicular returned. The return value of this is an array of two points: [ {x:...,y:...}, {x:...,y:...} ].
*
*
*/
(function() {
if(typeof Math.sgn == "undefined") {
Math.sgn = function(x) { return x == 0 ? 0 : x > 0 ? 1 :-1; };
}
var Vectors = {
subtract : function(v1, v2) { return {x:v1.x - v2.x, y:v1.y - v2.y }; },
dotProduct : function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); },
square : function(v) { return Math.sqrt((v.x * v.x) + (v.y * v.y)); },
scale : function(v, s) { return {x:v.x * s, y:v.y * s }; }
},
maxRecursion = 64,
flatnessTolerance = Math.pow(2.0,-maxRecursion-1);
/**
* Calculates the distance that the point lies from the curve.
*
* @param point a point in the form {x:567, y:3342}
* @param curve a Bezier curve in the form [{x:..., y:...}, {x:..., y:...}, {x:..., y:...}, {x:..., y:...}]. note that this is currently
* hardcoded to assume cubiz beziers, but would be better off supporting any degree.
* @return a JS object literal containing location and distance, for example: {location:0.35, distance:10}. Location is analogous to the location
* argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from
* the point to the curve.
*/
var _distanceFromCurve = function(point, curve) {
var candidates = [],
w = _convertToBezier(point, curve),
degree = curve.length - 1, higherDegree = (2 * degree) - 1,
numSolutions = _findRoots(w, higherDegree, candidates, 0),
v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0;
for (var i = 0; i < numSolutions; i++) {
v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null));
var newDist = Vectors.square(v);
if (newDist < dist) {
dist = newDist;
t = candidates[i];
}
}
v = Vectors.subtract(point, curve[degree]);
newDist = Vectors.square(v);
if (newDist < dist) {
dist = newDist;
t = 1.0;
}
return {location:t, distance:dist};
};
/**
* finds the nearest point on the curve to the given point.
*/
var _nearestPointOnCurve = function(point, curve) {
var td = _distanceFromCurve(point, curve);
return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location};
};
var _convertToBezier = function(point, curve) {
var degree = curve.length - 1, higherDegree = (2 * degree) - 1,
c = [], d = [], cdTable = [], w = [],
z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ];
for (var i = 0; i <= degree; i++) c[i] = Vectors.subtract(curve[i], point);
for (var i = 0; i <= degree - 1; i++) {
d[i] = Vectors.subtract(curve[i+1], curve[i]);
d[i] = Vectors.scale(d[i], 3.0);
}
for (var row = 0; row <= degree - 1; row++) {
for (var column = 0; column <= degree; column++) {
if (!cdTable[row]) cdTable[row] = [];
cdTable[row][column] = Vectors.dotProduct(d[row], c[column]);
}
}
for (i = 0; i <= higherDegree; i++) {
if (!w[i]) w[i] = [];
w[i].y = 0.0;
w[i].x = parseFloat(i) / higherDegree;
}
var n = degree, m = degree-1;
for (var k = 0; k <= n + m; k++) {
var lb = Math.max(0, k - m),
ub = Math.min(k, n);
for (i = lb; i <= ub; i++) {
j = k - i;
w[i+j].y += cdTable[j][i] * z[j][i];
}
}
return w;
};
/**
* counts how many roots there are.
*/
var _findRoots = function(w, degree, t, depth) {
var left = [], right = [],
left_count, right_count,
left_t = [], right_t = [];
switch (_getCrossingCount(w, degree)) {
case 0 : {
return 0;
}
case 1 : {
if (depth >= maxRecursion) {
t[0] = (w[0].x + w[degree].x) / 2.0;
return 1;
}
if (_isFlatEnough(w, degree)) {
t[0] = _computeXIntercept(w, degree);
return 1;
}
break;
}
}
_bezier(w, degree, 0.5, left, right);
left_count = _findRoots(left, degree, left_t, depth+1);
right_count = _findRoots(right, degree, right_t, depth+1);
for (var i = 0; i < left_count; i++) t[i] = left_t[i];
for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i];
return (left_count+right_count);
};
var _getCrossingCount = function(curve, degree) {
var n_crossings = 0, sign, old_sign;
sign = old_sign = Math.sgn(curve[0].y);
for (var i = 1; i <= degree; i++) {
sign = Math.sgn(curve[i].y);
if (sign != old_sign) n_crossings++;
old_sign = sign;
}
return n_crossings;
};
var _isFlatEnough = function(curve, degree) {
var error,
intercept_1, intercept_2, left_intercept, right_intercept,
a, b, c, det, dInv, a1, b1, c1, a2, b2, c2;
a = curve[0].y - curve[degree].y;
b = curve[degree].x - curve[0].x;
c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y;
var max_distance_above = max_distance_below = 0.0;
for (var i = 1; i < degree; i++) {
var value = a * curve[i].x + b * curve[i].y + c;
if (value > max_distance_above)
max_distance_above = value;
else if (value < max_distance_below)
max_distance_below = value;
}
a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b;
c2 = c - max_distance_above;
det = a1 * b2 - a2 * b1;
dInv = 1.0/det;
intercept_1 = (b1 * c2 - b2 * c1) * dInv;
a2 = a; b2 = b; c2 = c - max_distance_below;
det = a1 * b2 - a2 * b1;
dInv = 1.0/det;
intercept_2 = (b1 * c2 - b2 * c1) * dInv;
left_intercept = Math.min(intercept_1, intercept_2);
right_intercept = Math.max(intercept_1, intercept_2);
error = right_intercept - left_intercept;
return (error < flatnessTolerance)? 1 : 0;
};
var _computeXIntercept = function(curve, degree) {
var XLK = 1.0, YLK = 0.0,
XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y,
XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0,
det = XNM*YLK - YNM*XLK, detInv = 1.0/det,
S = (XNM*YMK - YNM*XMK) * detInv;
return 0.0 + XLK * S;
};
var _bezier = function(curve, degree, t, left, right) {
var temp = [[]];
for (var j =0; j <= degree; j++) temp[0][j] = curve[j];
for (var i = 1; i <= degree; i++) {
for (var j =0 ; j <= degree - i; j++) {
if (!temp[i]) temp[i] = [];
if (!temp[i][j]) temp[i][j] = {};
temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x;
temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y;
}
}
if (left != null)
for (j = 0; j <= degree; j++) left[j] = temp[j][0];
if (right != null)
for (j = 0; j <= degree; j++) right[j] = temp[degree-j][j];
return (temp[degree][0]);
};
var _curveFunctionCache = {};
var _getCurveFunctions = function(order) {
var fns = _curveFunctionCache[order];
if (!fns) {
fns = [];
var f_term = function() { return function(t) { return Math.pow(t, order); }; },
l_term = function() { return function(t) { return Math.pow((1-t), order); }; },
c_term = function(c) { return function(t) { return c; }; },
t_term = function() { return function(t) { return t; }; },
one_minus_t_term = function() { return function(t) { return 1-t; }; },
_termFunc = function(terms) {
return function(t) {
var p = 1;
for (var i = 0; i < terms.length; i++) p = p * terms[i](t);
return p;
};
};
fns.push(new f_term()); // first is t to the power of the curve order
for (var i = 1; i < order; i++) {
var terms = [new c_term(order)];
for (var j = 0 ; j < (order - i); j++) terms.push(new t_term());
for (var j = 0 ; j < i; j++) terms.push(new one_minus_t_term());
fns.push(new _termFunc(terms));
}
fns.push(new l_term()); // last is (1-t) to the power of the curve order
_curveFunctionCache[order] = fns;
}
return fns;
};
/**
* calculates a point on the curve, for a Bezier of arbitrary order.
* @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points.
* @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive.
*/
var _pointOnPath = function(curve, location) {
var cc = _getCurveFunctions(curve.length - 1),
_x = 0, _y = 0;
for (var i = 0; i < curve.length ; i++) {
_x = _x + (curve[i].x * cc[i](location));
_y = _y + (curve[i].y * cc[i](location));
}
return {x:_x, y:_y};
};
var _dist = function(p1,p2) {
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
};
var _isPoint = function(curve) {
return curve[0].x == curve[1].x && curve[0].y == curve[1].y;
};
/**
* finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also
* its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the
* point.
*/
var _pointAlongPath = function(curve, location, distance) {
if (_isPoint(curve)) {
return {
point:curve[0],
location:location
};
}
var prev = _pointOnPath(curve, location),
tally = 0,
curLoc = location,
direction = distance > 0 ? 1 : -1,
cur = null;
while (tally < Math.abs(distance)) {
curLoc += (0.005 * direction);
cur = _pointOnPath(curve, curLoc);
tally += _dist(cur, prev);
prev = cur;
}
return {point:cur, location:curLoc};
};
var _length = function(curve) {
if (_isPoint(curve)) return 0;
var prev = _pointOnPath(curve, 0),
tally = 0,
curLoc = 0,
direction = 1,
cur = null;
while (curLoc < 1) {
curLoc += (0.005 * direction);
cur = _pointOnPath(curve, curLoc);
tally += _dist(cur, prev);
prev = cur;
}
return tally;
};
/**
* finds the point that is 'distance' along the path from 'location'.
*/
var _pointAlongPathFrom = function(curve, location, distance) {
return _pointAlongPath(curve, location, distance).point;
};
/**
* finds the location that is 'distance' along the path from 'location'.
*/
var _locationAlongPathFrom = function(curve, location, distance) {
return _pointAlongPath(curve, location, distance).location;
};
/**
* returns the gradient of the curve at the given location, which is a decimal between 0 and 1 inclusive.
*
* thanks // http://bimixual.org/AnimationLibrary/beziertangents.html
*/
var _gradientAtPoint = function(curve, location) {
var p1 = _pointOnPath(curve, location),
p2 = _pointOnPath(curve.slice(0, curve.length - 1), location),
dy = p2.y - p1.y, dx = p2.x - p1.x;
return dy == 0 ? Infinity : Math.atan(dy / dx);
};
/**
returns the gradient of the curve at the point which is 'distance' from the given location.
if this point is greater than location 1, the gradient at location 1 is returned.
if this point is less than location 0, the gradient at location 0 is returned.
*/
var _gradientAtPointAlongPathFrom = function(curve, location, distance) {
var p = _pointAlongPath(curve, location, distance);
if (p.location > 1) p.location = 1;
if (p.location < 0) p.location = 0;
return _gradientAtPoint(curve, p.location);
};
/**
* calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location.
* if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero).
*/
var _perpendicularToPathAt = function(curve, location, length, distance) {
distance = distance == null ? 0 : distance;
var p = _pointAlongPath(curve, location, distance),
m = _gradientAtPoint(curve, p.location),
_theta2 = Math.atan(-1 / m),
y = length / 2 * Math.sin(_theta2),
x = length / 2 * Math.cos(_theta2);
return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}];
};
var jsBezier = window.jsBezier = {
distanceFromCurve : _distanceFromCurve,
gradientAtPoint : _gradientAtPoint,
gradientAtPointAlongCurveFrom : _gradientAtPointAlongPathFrom,
nearestPointOnCurve : _nearestPointOnCurve,
pointOnCurve : _pointOnPath,
pointAlongCurveFrom : _pointAlongPathFrom,
perpendicularToCurveAt : _perpendicularToPathAt,
locationAlongCurveFrom:_locationAlongPathFrom,
getLength:_length
};
})();
/**
* Biltong v0.2
*
* Various geometry functions written as part of jsPlumb and perhaps useful for others.
*
* Copyright (c) 2014 Simon Porritt
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
;(function() {
"use strict";
var Biltong = this.Biltong = {};
var _isa = function(a) { return Object.prototype.toString.call(a) === "[object Array]"; },
_pointHelper = function(p1, p2, fn) {
p1 = _isa(p1) ? p1 : [p1.x, p1.y];
p2 = _isa(p2) ? p2 : [p2.x, p2.y];
return fn(p1, p2);
},
/**
* @name Biltong.gradient
* @function
* @desc Calculates the gradient of a line between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The gradient of a line between the two points.
*/
_gradient = Biltong.gradient = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
if (_p2[0] == _p1[0])
return _p2[1] > _p1[1] ? Infinity : -Infinity;
else if (_p2[1] == _p1[1])
return _p2[0] > _p1[0] ? 0 : -0;
else
return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]);
});
},
/**
* @name Biltong.normal
* @function
* @desc Calculates the gradient of a normal to a line between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The gradient of a normal to a line between the two points.
*/
_normal = Biltong.normal = function(p1, p2) {
return -1 / _gradient(p1, p2);
},
/**
* @name Biltong.lineLength
* @function
* @desc Calculates the length of a line between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The length of a line between the two points.
*/
_lineLength = Biltong.lineLength = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2));
});
},
/**
* @name Biltong.quadrant
* @function
* @desc Calculates the quadrant in which the angle between the two points lies.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Integer} The quadrant - 1 for upper right, 2 for lower right, 3 for lower left, 4 for upper left.
*/
_quadrant = Biltong.quadrant = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
if (_p2[0] > _p1[0]) {
return (_p2[1] > _p1[1]) ? 2 : 1;
}
else if (_p2[0] == _p1[0]) {
return _p2[1] > _p1[1] ? 2 : 1;
}
else {
return (_p2[1] > _p1[1]) ? 3 : 4;
}
});
},
/**
* @name Biltong.theta
* @function
* @desc Calculates the angle between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The angle between the two points.
*/
_theta = Biltong.theta = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
var m = _gradient(_p1, _p2),
t = Math.atan(m),
s = _quadrant(_p1, _p2);
if ((s == 4 || s== 3)) t += Math.PI;
if (t < 0) t += (2 * Math.PI);
return t;
});
},
/**
* @name Biltong.intersects
* @function
* @desc Calculates whether or not the two rectangles intersect.
* @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @return {Boolean} True if the rectangles intersect, false otherwise.
*/
_intersects = Biltong.intersects = function(r1, r2) {
var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h;
return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) ||
( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) );
},
/**
* @name Biltong.encloses
* @function
* @desc Calculates whether or not r2 is completely enclosed by r1.
* @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @param {Boolean} [allowSharedEdges=false] If true, the concept of enclosure allows for one or more edges to be shared by the two rectangles.
* @return {Boolean} True if r1 encloses r2, false otherwise.
*/
_encloses = Biltong.encloses = function(r1, r2, allowSharedEdges) {
var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h,
c = function(v1, v2, v3, v4) { return allowSharedEdges ? v1 <= v2 && v3>= v4 : v1 < v2 && v3 > v4; };
return c(x1,a1,x2,a2) && c(y1,b1,y2,b2);
},
_segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
_inverseSegmentMultipliers = [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
/**
* @name Biltong.pointOnLine
* @function
* @desc Calculates a point on the line from `fromPoint` to `toPoint` that is `distance` units along the length of the line.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Point} Point on the line, in the form `{ x:..., y:... }`.
*/
_pointOnLine = Biltong.pointOnLine = function(fromPoint, toPoint, distance) {
var m = _gradient(fromPoint, toPoint),
s = _quadrant(fromPoint, toPoint),
segmentMultiplier = distance > 0 ? _segmentMultipliers[s] : _inverseSegmentMultipliers[s],
theta = Math.atan(m),
y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
return { x:fromPoint.x + x, y:fromPoint.y + y };
},
/**
* @name Biltong.perpendicularLineTo
* @function
* @desc Calculates a line of length `length` that is perpendicular to the line from `fromPoint` to `toPoint` and passes through `toPoint`.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Line} Perpendicular line, in the form `[ { x:..., y:... }, { x:..., y:... } ]`.
*/
_perpendicularLineTo = Biltong.perpendicularLineTo = function(fromPoint, toPoint, length) {
var m = _gradient(fromPoint, toPoint),
theta2 = Math.atan(-1 / m),
y = length / 2 * Math.sin(theta2),
x = length / 2 * Math.cos(theta2);
return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
};
}).call(this);
;(function() {
"use strict";
var Sniff = {
android:navigator.userAgent.toLowerCase().indexOf("android") > -1
};
var matchesSelector = function(el, selector, ctx) {
ctx = ctx || el.parentNode;
var possibles = ctx.querySelectorAll(selector);
for (var i = 0; i < possibles.length; i++) {
if (possibles[i] === el) {
return true;
}
}
return false;
},
_gel = function(el) { return typeof el == "string" ? document.getElementById(el) : el; },
_t = function(e) { return e.srcElement || e.target; },
_d = function(l, fn) {
for (var i = 0, j = l.length; i < j; i++) {
if (l[i] == fn) break;
}
if (i < l.length) l.splice(i, 1);
},
guid = 1,
//
// this function generates a guid for every handler, sets it on the handler, then adds
// it to the associated object's map of handlers for the given event. this is what enables us
// to unbind all events of some type, or all events (the second of which can be requested by the user,
// but it also used by Mottle when an element is removed.)
_store = function(obj, event, fn) {
var g = guid++;
obj.__ta = obj.__ta || {};
obj.__ta[event] = obj.__ta[event] || {};
// store each handler with a unique guid.
obj.__ta[event][g] = fn;
// set the guid on the handler.
fn.__tauid = g;
return g;
},
_unstore = function(obj, event, fn) {
obj.__ta && obj.__ta[event] && delete obj.__ta[event][fn.__tauid];
// a handler might have attached extra functions, so we unbind those too.
if (fn.__taExtra) {
for (var i = 0; i < fn.__taExtra.length; i++) {
_unbind(obj, fn.__taExtra[i][0], fn.__taExtra[i][1]);
}
fn.__taExtra.length = 0;
}
// a handler might have attached an unstore callback
fn.__taUnstore && fn.__taUnstore();
},
_curryChildFilter = function(children, obj, fn, evt) {
if (children == null) return fn;
else {
var c = children.split(","),
_fn = function(e) {
_fn.__tauid = fn.__tauid;
var t = _t(e);
for (var i = 0; i < c.length; i++) {
if (matchesSelector(t, c[i], obj)) {
fn.apply(t, arguments);
}
}
};
registerExtraFunction(fn, evt, _fn);
return _fn;
}
},
//
// registers an 'extra' function on some event listener function we were given - a function that we
// created and bound to the element as part of our housekeeping, and which we want to unbind and remove
// whenever the given function is unbound.
registerExtraFunction = function(fn, evt, newFn) {
fn.__taExtra = fn.__taExtra || [];
fn.__taExtra.push([evt, newFn]);
},
DefaultHandler = function(obj, evt, fn, children) {
// TODO: this was here originally because i wanted to handle devices that are both touch AND mouse. however this can cause certain of the helper
// functions to be bound twice, as - for example - on a nexus 4, both a mouse event and a touch event are fired. the use case i had in mind
// was a device such as an Asus touch pad thing, which has a touch pad but can also be controlled with a mouse.
//if (isMouseDevice)
// _bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn);
if (isTouchDevice && touchMap[evt]) {
_bind(obj, touchMap[evt], _curryChildFilter(children, obj, fn, touchMap[evt]), fn);
}
else
_bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn);
},
SmartClickHandler = function(obj, evt, fn, children) {
if (obj.__taSmartClicks == null) {
var down = function(e) { obj.__tad = _pageLocation(e); },
up = function(e) { obj.__tau = _pageLocation(e); },
click = function(e) {
if (obj.__tad && obj.__tau && obj.__tad[0] === obj.__tau[0] && obj.__tad[1] === obj.__tau[1]) {
for (var i = 0; i < obj.__taSmartClicks.length; i++)
obj.__taSmartClicks[i].apply(_t(e), [ e ]);
}
};
DefaultHandler(obj, "mousedown", down, children);
DefaultHandler(obj, "mouseup", up, children);
DefaultHandler(obj, "click", click, children);
obj.__taSmartClicks = [];
}
// store in the list of callbacks
obj.__taSmartClicks.push(fn);
// the unstore function removes this function from the object's listener list for this type.
fn.__taUnstore = function() {
_d(obj.__taSmartClicks, fn);
};
},
_tapProfiles = {
"tap":{touches:1, taps:1},
"dbltap":{touches:1, taps:2},
"contextmenu":{touches:2, taps:1}
},
TapHandler = function(clickThreshold, dblClickThreshold) {
return function(obj, evt, fn, children) {
// if event is contextmenu, for devices which are mouse only, we want to
// use the default bind.
if (evt == "contextmenu" && isMouseDevice)
DefaultHandler(obj, evt, fn, children);
else {
// the issue here is that this down handler gets registered only for the
// child nodes in the first registration. in fact it should be registered with
// no child selector and then on down we should cycle through the regustered
// functions to see if one of them matches. on mouseup we should execute ALL of
// the functions whose children are either null or match the element.
if (obj.__taTapHandler == null) {
var tt = obj.__taTapHandler = {
tap:[],
dbltap:[],
contextmenu:[],
down:false,
taps:0,
downSelectors:[]
};
var down = function(e) {
var target = e.srcElement || e.target;
for (var i = 0; i < tt.downSelectors.length; i++) {
if (tt.downSelectors[i] == null || matchesSelector(target, tt.downSelectors[i], obj)) {
tt.down = true;
setTimeout(clearSingle, clickThreshold);
setTimeout(clearDouble, dblClickThreshold);
break; // we only need one match on mousedown
}
}
},
up = function(e) {
if (tt.down) {
var target = e.srcElement || e.target;
tt.taps++;
var tc = _touchCount(e);
for (var eventId in _tapProfiles) {
var p = _tapProfiles[eventId];
if (p.touches === tc && (p.taps === 1 || p.taps === tt.taps)) {
for (var i = 0; i < tt[eventId].length; i++) {
if (tt[eventId][i][1] == null || matchesSelector(target, tt[eventId][i][1], obj))
tt[eventId][i][0].apply(_t(e), [ e ]);
}
}
}
}
},
clearSingle = function() {
tt.down = false;
},
clearDouble = function() {
tt.taps = 0;
};
DefaultHandler(obj, "mousedown", down/*, children*/);
DefaultHandler(obj, "mouseup", up/*, children*/);
}
// add this child selector (it can be null, that's fine).
obj.__taTapHandler.downSelectors.push(children);
obj.__taTapHandler[evt].push([fn, children]);
// the unstore function removes this function from the object's listener list for this type.
fn.__taUnstore = function() {
_d(obj.__taTapHandler[evt], fn);
};
}
};
},
meeHelper = function(type, evt, obj, target) {
for (var i in obj.__tamee[type]) {
obj.__tamee[type][i].apply(target, [ evt ]);
}
},
MouseEnterExitHandler = function() {
var activeElements = [];
return function(obj, evt, fn, children) {
if (!obj.__tamee) {
// __tamee holds a flag saying whether the mouse is currently "in" the element, and a list of
// both mouseenter and mouseexit functions.
obj.__tamee = { over:false, mouseenter:[], mouseexit:[] };
// register over and out functions
var over = function(e) {
var t = _t(e);
if ( (children== null && (t == obj && !obj.__tamee.over)) || (matchesSelector(t, children, obj) && (t.__tamee == null || !t.__tamee.over)) ) {
meeHelper("mouseenter", e, obj, t);
t.__tamee = t.__tamee || {};
t.__tamee.over = true;
activeElements.push(t);
}
},
out = function(e) {
var t = _t(e);
// is the current target one of the activeElements? and is the
// related target NOT a descendant of it?
for (var i = 0; i < activeElements.length; i++) {
if (t == activeElements[i] && !matchesSelector((e.relatedTarget || e.toElement), "*", t)) {
t.__tamee.over = false;
activeElements.splice(i, 1);
meeHelper("mouseexit", e, obj, t);
}
}
};
_bind(obj, "mouseover", _curryChildFilter(children, obj, over, "mouseover"), over);
_bind(obj, "mouseout", _curryChildFilter(children, obj, out, "mouseout"), out);
}
fn.__taUnstore = function() {
delete obj.__tamee[evt][fn.__tauid];
};
_store(obj, evt, fn);
obj.__tamee[evt][fn.__tauid] = fn;
};
},
isTouchDevice = "ontouchstart" in document.documentElement,
isMouseDevice = "onmousedown" in document.documentElement,
touchMap = { "mousedown":"touchstart", "mouseup":"touchend", "mousemove":"touchmove" },
touchstart="touchstart",touchend="touchend",touchmove="touchmove",
ta_down = "__MottleDown", ta_up = "__MottleUp",
ta_context_down = "__MottleContextDown", ta_context_up = "__MottleContextUp",
iev = (function() {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent,
re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
})(),
isIELT9 = iev > -1 && iev < 9,
_genLoc = function(e, prefix) {
if (e == null) return [ 0, 0 ];
var ts = _touches(e), t = _getTouch(ts, 0);
return [t[prefix + "X"], t[prefix + "Y"]];
},
_pageLocation = function(e) {
if (e == null) return [ 0, 0 ];
if (isIELT9) {
return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ];
}
else {
return _genLoc(e, "page");
}
},
_screenLocation = function(e) {
return _genLoc(e, "screen");
},
_clientLocation = function(e) {
return _genLoc(e, "client");
},
_getTouch = function(touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; },
_touches = function(e) {
return e.touches && e.touches.length > 0 ? e.touches :
e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
[ e ];
},
_touchCount = function(e) { return _touches(e).length; },
//http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
_bind = function( obj, type, fn, originalFn) {
_store(obj, type, fn);
originalFn.__tauid = fn.__tauid;
if (obj.addEventListener)
obj.addEventListener( type, fn, false );
else if (obj.attachEvent) {
var key = type + fn.__tauid;
obj["e" + key] = fn;
// TODO look at replacing with .call(..)
obj[key] = function() {
obj["e"+key] && obj["e"+key]( window.event );
};
obj.attachEvent( "on"+type, obj[key] );
}
},
_unbind = function( obj, type, fn) {
if (fn == null) return;
_each(obj, function() {
var _el = _gel(this);
_unstore(_el, type, fn);
// it has been bound if there is a tauid. otherwise it was not bound and we can ignore it.
if (fn.__tauid != null) {
if (_el.removeEventListener)
_el.removeEventListener( type, fn, false );
else if (this.detachEvent) {
var key = type + fn.__tauid;
_el[key] && _el.detachEvent( "on"+type, _el[key] );
_el[key] = null;
_el["e"+key] = null;
}
}
});
},
_devNull = function() {},
_each = function(obj, fn) {
if (obj == null) return;
// if a list (or list-like), use it. if a string, get a list
// by running the string through querySelectorAll. else, assume
// it's an Element.
obj = (typeof obj !== "string") && (obj.tagName == null && obj.length != null) ? obj : typeof obj === "string" ? document.querySelectorAll(obj) : [ obj ];
for (var i = 0; i < obj.length; i++)
fn.apply(obj[i]);
};
/**
* Event handler. Offers support for abstracting out the differences
* between touch and mouse devices, plus "smart click" functionality
* (don't fire click if the mouse has moved betweeb mousedown and mouseup),
* and synthesized click/tap events.
* @class Mottle
* @constructor
* @param {Object} params Constructor params
* @param {Integer} [params.clickThreshold=150] Threshold, in milliseconds beyond which a touchstart followed by a touchend is not considered to be a click.
* @param {Integer} [params.dblClickThreshold=350] Threshold, in milliseconds beyond which two successive tap events are not considered to be a click.
* @param {Boolean} [params.smartClicks=false] If true, won't fire click events if the mouse has moved between mousedown and mouseup. Note that this functionality
* requires that Mottle consume the mousedown event, and so may not be viable in all use cases.
*/
this.Mottle = function(params) {
params = params || {};
var self = this,
clickThreshold = params.clickThreshold || 150,
dblClickThreshold = params.dblClickThreshold || 350,
mouseEnterExitHandler = new MouseEnterExitHandler(),
tapHandler = new TapHandler(clickThreshold, dblClickThreshold),
_smartClicks = params.smartClicks,
_doBind = function(obj, evt, fn, children) {
if (fn == null) return;
_each(obj, function() {
var _el = _gel(this);
if (_smartClicks && evt === "click")
SmartClickHandler(_el, evt, fn, children);
else if (evt === "tap" || evt === "dbltap" || evt === "contextmenu") {
tapHandler(_el, evt, fn, children);
}
else if (evt === "mouseenter" || evt == "mouseexit")
mouseEnterExitHandler(_el, evt, fn, children);
else
DefaultHandler(_el, evt, fn, children);
});
};
/**
* Removes an element from the DOM, and unregisters all event handlers for it. You should use this
* to ensure you don't leak memory.
* @method remove
* @param {String|Element} el Element, or id of the element, to remove.
* @return {Mottle} The current Mottle instance; you can chain this method.
*/
this.remove = function(el) {
_each(el, function() {
var _el = _gel(this);
if (_el.__ta) {
for (var evt in _el.__ta) {
for (var h in _el.__ta[evt]) {
_unbind(_el, evt, _el.__ta[evt][h]);
}
}
}
_el.parentNode && _el.parentNode.removeChild(_el);
});