This repository was archived by the owner on May 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 865
/
Copy pathinteractive.js
4353 lines (3772 loc) · 164 KB
/
interactive.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
/* TODO(csilvers): fix these lint errors (http://eslint.org/docs/rules): */
/* eslint-disable comma-dangle, indent, max-len, no-redeclare, no-undef, no-var, one-var, prefer-spread, space-infix-ops, space-unary-ops */
/* To fix, remove an entry above, run ka-lint, and fix errors. */
define(function(require) {
require("../third_party/jquery.mobile.vmouse.js");
require("./graphie.js");
var kvector = require("./kvector.js");
var kpoint = require("./kpoint.js");
var kline = require("./kline.js");
var WrappedEllipse = require("./wrapped-ellipse.js");
var WrappedLine = require("./wrapped-line.js");
var WrappedPath = require("./wrapped-path.js");
function sum(array) {
return _.reduce(array, function(memo, arg) { return memo + arg; }, 0);
}
function clockwise(points) {
var segments = _.zip(points, points.slice(1).concat(points.slice(0, 1)));
var areas = _.map(segments, function(segment) {
var p1 = segment[0], p2 = segment[1];
return (p2[0] - p1[0]) * (p2[1] + p1[1]);
});
return sum(areas) > 0;
}
/* vector-add multiple [x, y] coords/vectors */
function addPoints() {
var points = _.toArray(arguments);
var zipped = _.zip.apply(_, points);
return _.map(zipped, sum);
}
function reverseVector(vector) {
return _.map(vector, function(coord) {
return coord * -1;
});
}
function scaledDistanceFromAngle(angle) {
// constants based on the magic numbers from graphie.addTriangle()
var a = 3.51470560176242 * 20;
var b = 0.5687298702748785 * 20;
var c = -0.037587715462826674;
return (a - b) * Math.exp(c * angle) + b;
}
function scaledPolarRad(radius, radians) {
return [
radius * Math.cos(radians),
radius * Math.sin(radians) * -1 // SVG flips y axis
];
}
function scaledPolarDeg(radius, degrees) {
var radians = degrees * Math.PI / 180;
return scaledPolarRad(radius, radians);
}
$.extend(KhanUtil, {
// Fill opacity for inequality shading
FILL_OPACITY: 0.3,
// TODO(alpert): Should this be a global?
dragging: false,
createSorter: function() {
var sorter = {};
var list;
sorter.hasAttempted = false;
sorter.init = function(element) {
list = $("[id=" + element + "]").last();
var container = list.wrap("<div>").parent();
var placeholder = $("<li>");
placeholder.addClass("placeholder");
container.addClass("sortable ui-helper-clearfix");
list.find("li").each(function(tileNum, tile) {
$(tile).bind("vmousedown", function(event) {
if (event.type === "vmousedown" && (event.which === 1 || event.which === 0)) {
event.preventDefault();
$(tile).addClass("dragging");
var tileIndex = $(this).index();
placeholder.insertAfter(tile);
placeholder.width($(tile).width());
$(this).css("z-index", 100);
var offset = $(this).offset();
var click = {
left: event.pageX - offset.left - 3,
top: event.pageY - offset.top - 3
};
$(tile).css({ position: "absolute" });
$(tile).offset({
left: offset.left,
top: offset.top
});
$(document).bind("vmousemove.tile vmouseup.tile", function(event) {
event.preventDefault();
if (event.type === "vmousemove") {
sorter.hasAttempted = true;
$(tile).offset({
left: event.pageX - click.left,
top: event.pageY - click.top
});
var leftEdge = list.offset().left;
var midWidth = $(tile).offset().left - leftEdge;
var index = 0;
var sumWidth = 0;
list.find("li").each(function() {
if (this === placeholder[0] || this === tile) {
return;
}
if (midWidth > sumWidth + $(this).outerWidth(true) / 2) {
index += 1;
}
sumWidth += $(this).outerWidth(true);
});
if (index !== tileIndex) {
tileIndex = index;
if (index === 0) {
placeholder.prependTo(list);
$(tile).prependTo(list);
} else {
placeholder.detach();
$(tile).detach();
var preceeding = list.find("li")[index - 1];
placeholder.insertAfter(preceeding);
$(tile).insertAfter(preceeding);
}
}
} else if (event.type === "vmouseup") {
$(document).unbind(".tile");
var position = $(tile).offset();
$(position).animate(placeholder.offset(), {
duration: 150,
step: function(now, fx) {
position[fx.prop] = now;
$(tile).offset(position);
},
complete: function() {
$(tile).css("z-index", 0);
placeholder.detach();
$(tile).css({ position: "static" });
$(tile).removeClass("dragging");
}
});
}
});
}
});
});
};
sorter.getContent = function() {
var content = [];
list.find("li").each(function(tileNum, tile) {
content.push($.trim($(tile).find(".sort-key").text()));
});
return content;
};
sorter.setContent = function(content) {
var tiles = [];
$.each(content, function(n, sortKey) {
var tile = list.find("li .sort-key").filter(function() {
// sort-key must match exactly
return $(this).text() === sortKey;
}).closest("li").get(0);
$(tile).detach(); // remove matched tile so you can have duplicates
tiles.push(tile);
});
list.append(tiles);
};
return sorter;
},
// Useful for shapes that are only sometimes drawn. If a shape isn't
// needed, it can be replaced with bogusShape which just has stub methods
// that successfully do nothing.
// The alternative would be 'if..typeof' checks all over the place.
bogusShape: {
animate: function() {},
attr: function() {},
remove: function() {}
}
});
$.extend(KhanUtil.Graphie.prototype, {
// Wrap graphInit to create a fixed-size graph automatically scaled to the given range
initAutoscaledGraph: function(range, options) {
var graph = this;
options = $.extend({
xpixels: 500,
ypixels: 500,
xdivisions: 20,
ydivisions: 20,
labels: true,
unityLabels: true,
range: (range === undefined ? [[-10, 10], [-10, 10]] : range)
}, options);
options.scale = [
options.xpixels / (options.range[0][1] - options.range[0][0]),
options.ypixels / (options.range[1][1] - options.range[1][0])
];
options.gridStep = [
(options.range[0][1] - options.range[0][0]) / options.xdivisions,
(options.range[1][1] - options.range[1][0]) / options.ydivisions
];
// Attach the resulting metrics to the graph for later reference
graph.xpixels = options.xpixels;
graph.ypixels = options.ypixels;
graph.range = options.range;
graph.scale = options.scale;
graph.graphInit(options);
},
// graphie puts text spans on top of the SVG, which looks good, but gets
// in the way of mouse events. This adds another SVG element on top
// of everything else where we can add invisible shapes with mouse
// handlers wherever we want.
addMouseLayer: function(options) {
var graph = this;
options = _.extend({
allowScratchpad: false
}, options);
var mouselayerZIndex = 2;
graph.mouselayer = Raphael(graph.raphael.canvas.parentNode, graph.xpixels, graph.ypixels);
$(graph.mouselayer.canvas).css("z-index", mouselayerZIndex);
if (options.onClick || options.onMouseDown || options.onMouseMove ||
options.onMouseOver || options.onMouseOut) {
var canvasClickTarget = graph.mouselayer.rect(
0, 0, graph.xpixels, graph.ypixels).attr({
fill: "#000",
opacity: 0
});
var isClickingCanvas = false;
$(graph.mouselayer.canvas).on("vmousedown", function(e) {
if (e.target === canvasClickTarget[0]) {
if (options.onMouseDown) {
options.onMouseDown(graph.getMouseCoord(e));
}
isClickingCanvas = true;
if (options.onMouseMove) {
$(document).bind("vmousemove.mouseLayer", function(e) {
if (isClickingCanvas) {
e.preventDefault();
options.onMouseMove(graph.getMouseCoord(e));
}
});
}
$(document).bind("vmouseup.mouseLayer", function(e) {
$(document).unbind(".mouseLayer");
// Only register clicks that started on the canvas, and not
// on another mouseLayer target
if (isClickingCanvas && options.onClick) {
options.onClick(graph.getMouseCoord(e));
}
isClickingCanvas = false;
});
}
});
if (options.onMouseOver) {
$(graph.mouselayer.canvas).on("vmouseover", function(e) {
options.onMouseOver(graph.getMouseCoord(e));
});
}
if (options.onMouseOut) {
$(graph.mouselayer.canvas).on("vmouseout", function(e) {
options.onMouseOut(graph.getMouseCoord(e));
});
}
}
if (!options.allowScratchpad) {
Khan.scratchpad.disable();
}
// Add mouse and visible wrapper layers for DOM-node-wrapped movables
graph._mouselayerWrapper = document.createElement("div");
$(graph._mouselayerWrapper).css({
position: "absolute",
left: 0,
top: 0,
zIndex: mouselayerZIndex
});
graph._visiblelayerWrapper = document.createElement("div");
$(graph._visiblelayerWrapper).css({
position: "absolute",
left: 0,
top: 0
});
var el = graph.raphael.canvas.parentNode;
el.appendChild(graph._visiblelayerWrapper);
el.appendChild(graph._mouselayerWrapper);
// Add functions for adding to wrappers
graph.addToMouseLayerWrapper = function(el) {
this._mouselayerWrapper.appendChild(el);
};
graph.addToVisibleLayerWrapper = function(el) {
this._visiblelayerWrapper.appendChild(el);
};
},
/**
* Get mouse coordinates in pixels
*/
getMousePx: function(event) {
var graphie = this;
// mouse{X|Y} is in pixels relative to the SVG
var mouseX = event.pageX - $(graphie.raphael.
canvas.parentNode).offset().left;
var mouseY = event.pageY - $(graphie.raphael.
canvas.parentNode).offset().top;
return [mouseX, mouseY];
},
/**
* Get mouse coordinates in graph coordinates
*/
getMouseCoord: function(event) {
return this.unscalePoint(this.getMousePx(event));
},
// Draw angle arcs
drawArcs: function(point1, vertex, point3, numArcs) {
var startAngle = KhanUtil.findAngle(point1, vertex);
var endAngle = KhanUtil.findAngle(point3, vertex);
if (((endAngle - startAngle) % 360 + 360) % 360 > 180) {
var temp = startAngle;
startAngle = endAngle;
endAngle = temp;
}
var radius = 0.3;
// smaller angles need a bigger radius
if ((((endAngle - startAngle) % 360 + 360) % 360) < 75) {
radius = (-0.6 / 90) * (((endAngle - startAngle) % 360 + 360) % 360) + 0.8;
}
var arcset = [];
for (var arc = 0; arc < numArcs; ++arc) {
arcset.push(this.arc(vertex, radius + (0.15 * arc), startAngle, endAngle));
}
return arcset;
},
/**
* Unlike all other Graphie-related code, the following three functions use
* a lot of scaled coordinates (so that labels appear the same size
* regardless of current shape/figure scale). These are prefixed with 's'.
*/
labelAngle: function(options) {
var graphie = this;
_.defaults(options, {
point1: [0, 0],
vertex: [0, 0],
point3: [0, 0],
label: null,
numArcs: 1,
showRightAngleMarker: true,
pushOut: 0,
clockwise: false,
style: {}
});
// Allow null text to hide the 90 degree angle marker
var text = (options.text === undefined) ? "" : options.text;
var vertex = options.vertex;
var sVertex = graphie.scalePoint(vertex);
var p1, p3;
if (options.clockwise) {
p1 = options.point1;
p3 = options.point3;
} else {
p1 = options.point3;
p3 = options.point1;
}
// TODO(alex): more spacing if >= 100 degrees (due to +1 character)
// also take into account angle vs. text orientation, if possible
// Calculate angles
var startAngle = KhanUtil.findAngle(p1, vertex);
var endAngle = KhanUtil.findAngle(p3, vertex);
var angle = (endAngle + 360 - startAngle) % 360;
var halfAngle = (startAngle + angle / 2) % 360;
// Calculate distance from angle
var sPadding = 5 * options.pushOut;
var sRadius = sPadding + scaledDistanceFromAngle(angle);
var temp = [];
if (Math.abs(angle - 90) < 1e-9 && options.showRightAngleMarker) {
// Draw right angle box
var v1 = addPoints(sVertex, scaledPolarDeg(sRadius, startAngle));
var v2 = addPoints(sVertex, scaledPolarDeg(sRadius, endAngle));
sRadius *= Math.SQRT2;
var v3 = addPoints(sVertex, scaledPolarDeg(sRadius, halfAngle));
_.each([v1, v2], function(v) {
temp.push(graphie.scaledPath([v, v3], options.style));
});
} else {
// Draw arcs
_.times(options.numArcs, function(i) {
temp.push(graphie.arc(
vertex,
graphie.unscaleVector(sRadius),
startAngle,
endAngle,
options.style
));
sRadius += 3;
});
}
if (text) {
// Update label text
// Substitute actual angle measure for "$deg"
var match = text.match(/\$deg(\d)?/);
if (match) {
var precision = match[1] || 1;
text = text.replace(
match[0],
KhanUtil.toFixedApprox(angle, precision) + "^{\\circ}"
);
}
// Calculate label position
var sOffset = scaledPolarDeg(sRadius + 15, halfAngle);
var sPosition = addPoints(sVertex, sOffset);
var position = graphie.unscalePoint(sPosition);
// Reuse label if possible
if (options.label) {
options.label.setPosition(position);
options.label.processMath(text, /* force */ true);
} else {
graphie.label(position, text, "center", options.style);
}
}
return temp;
},
labelSide: function(options) {
var graphie = this;
_.defaults(options, {
point1: [0, 0],
point2: [0, 0],
label: null,
text: "",
numTicks: 0,
numArrows: 0,
clockwise: false,
style: {}
});
var p1, p2;
if (options.clockwise) {
p1 = options.point1;
p2 = options.point2;
} else {
p1 = options.point2;
p2 = options.point1;
}
var midpoint = [(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2];
var sMidpoint = graphie.scalePoint(midpoint);
var parallelAngle = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]);
var perpendicularAngle = parallelAngle + Math.PI / 2;
var temp = [];
var sCumulativeOffset = 0;
if (options.numTicks) {
// Draw ticks
var n = options.numTicks;
var sSpacing = 5;
var sHeight = 5;
var style = _.extend({}, options.style, {
strokeWidth: 2
});
_.times(n, function(i) {
var sOffset = sSpacing * (i - (n - 1) / 2);
var sOffsetVector = scaledPolarRad(sOffset, parallelAngle);
var sHeightVector = scaledPolarRad(sHeight, perpendicularAngle);
var sPath = [
addPoints(sMidpoint, sOffsetVector, sHeightVector),
addPoints(sMidpoint, sOffsetVector,
reverseVector(sHeightVector))
];
temp.push(graphie.scaledPath(sPath, style));
});
sCumulativeOffset += sSpacing * (n - 1) + 15;
}
if (options.numArrows) {
// Draw arrows
var n = options.numArrows;
// Arrows always point up, unless horizontal (if so, point right)
var start = [p1, p2].sort(function(a, b) {
if (a[1] === b[1]) {
return a[0] - b[0];
} else {
return a[1] - b[1];
}
})[0];
var sStart = graphie.scalePoint(start);
var style = _.extend({}, options.style, {
arrows: "->",
strokeWidth: 2
});
var sSpacing = 5;
_.times(n, function(i) {
var sOffset = sCumulativeOffset + sSpacing * i;
var sOffsetVector = scaledPolarRad(sOffset, parallelAngle);
if (start !== p1) {
sOffsetVector = reverseVector(sOffsetVector);
}
var sEnd = addPoints(sMidpoint, sOffsetVector);
temp.push(graphie.scaledPath([sStart, sEnd], style));
});
}
var text = options.text;
if (text) {
// Update label text
// Substitute actual side length for "$len"
var match = text.match(/\$len(\d)?/);
if (match) {
var distance = KhanUtil.getDistance(p1, p2);
var precision = match[1] || 1;
text = text.replace(
match[0],
KhanUtil.toFixedApprox(distance, precision)
);
}
// Calculate label position
// distance needs to take into account length of label
// and perhaps orientation, to be smart about it
var sOffset = 20;
var sOffsetVector = scaledPolarRad(sOffset, perpendicularAngle);
var sPosition = addPoints(sMidpoint, sOffsetVector);
var position = graphie.unscalePoint(sPosition);
// Reuse label if possible
if (options.label) {
options.label.setPosition(position);
options.label.processMath(text, /* force */ true);
} else {
graphie.label(position, text, "center", options.style);
}
}
return temp;
},
/* Can also be used to label points that aren't vertices */
labelVertex: function(options) {
var graphie = this;
_.defaults(options, {
point1: null,
vertex: [0, 0],
point3: null,
label: null,
text: "",
clockwise: false,
style: {}
});
if (!options.text) {
return;
}
var vertex = options.vertex;
var sVertex = graphie.scalePoint(vertex);
var p1, p3;
if (options.clockwise) {
p1 = options.point1;
p3 = options.point3;
} else {
p1 = options.point3;
p3 = options.point1;
}
// Calculate label angle relative to vertex
var angle = 135;
var halfAngle;
if (p1 && p3) {
// Point within a polygon
var startAngle = KhanUtil.findAngle(p1, vertex);
var endAngle = KhanUtil.findAngle(p3, vertex);
angle = (endAngle + 360 - startAngle) % 360;
halfAngle = (startAngle + angle / 2 + 180) % 360;
} else if (p1) {
// Point on a line/segment
var parallelAngle = KhanUtil.findAngle(vertex, p1);
halfAngle = parallelAngle + 90;
} else if (p3) {
var parallelAngle = KhanUtil.findAngle(p3, vertex);
halfAngle = parallelAngle + 90;
} else {
// Standalone point
halfAngle = 135;
}
// Calculate label position
var sRadius = 10 + scaledDistanceFromAngle(360 - angle);
var sOffsetVector = scaledPolarDeg(sRadius, halfAngle);
var sPosition = addPoints(sVertex, sOffsetVector);
var position = graphie.unscalePoint(sPosition);
// Reuse label if possible
if (options.label) {
options.label.setPosition(position);
options.label.processMath(options.text, /* force */ true);
} else {
graphie.label(position, options.text, "center", options.style);
}
},
// Add a point to the graph that can be dragged around.
// It allows automatic constraints on its movement as well as automatically
// managing line segments that terminate at the point.
//
// Options can be set to control how the point behaves:
// coord[]:
// The initial position of the point
// snapX, snapY:
// The minimum increment the point can be moved
//
// The return value is an object that can be used to manipulate the point:
// The coordX and coordY properties tell you the current position
//
// By adding an onMove() method to the returned object, you can install an
// event handler that gets called every time the user moves the point.
//
// The returned object also provides a moveTo(x,y) method that will move
// the point to a specific coordinate
//
// Constraints can be set on the on the returned object:
//
// - Set point to be immovable:
// movablePoint.constraints.fixed = true
//
// - Constrain point to a fixed distance from another point. The resulting
// point will move in a circle:
// movablePoint.fixedDistance = {
// dist: 2,
// point: point1
// }
//
// - Constrain point to a line defined by a fixed angle between it and
// two other points:
// movablePoint.fixedAngle = {
// angle: 45,
// vertex: point1,
// ref: point2
// }
//
// - Confined the point to traveling in a vertical or horizontal line,
// respectively
// movablePoint.constrainX = true;
// movablePoint.constrainY = true;
//
// - Connect a movableLineSegment to a movablePoint. The point is attached
// to a specific end of the line segment by adding the segment either to
// the list of lines that start at the point or the list of lines that
// end at the point (movableLineSegment can do this for you):
// movablePoint.lineStarts.push(movableLineSegment);
// - or -
// movablePoint.lineEnds.push(movableLineSegment);
//
// - Connect a movablePolygon to a movablePoint in exacty the same way:
// movablePoint.polygonVertices.push(movablePolygon);
//
addMovablePoint: function(options) {
// The state object that gets returned
var movablePoint = $.extend(true, {
graph: this,
coord: [0, 0],
snapX: 0,
snapY: 0,
pointSize: 4,
highlight: false,
dragging: false,
visible: true,
bounded: true,
constraints: {
fixed: false,
constrainX: false,
constrainY: false,
fixedAngle: {},
fixedDistance: {}
},
lineStarts: [],
lineEnds: [],
polygonVertices: [],
normalStyle: {},
highlightStyle: {
fill: KhanUtil.INTERACTING,
stroke: KhanUtil.INTERACTING
},
labelStyle: {
color: KhanUtil.INTERACTIVE
},
vertexLabel: "",
mouseTarget: null
}, options);
var normalColor = (movablePoint.constraints.fixed) ?
KhanUtil.DYNAMIC
: KhanUtil.INTERACTIVE;
movablePoint.normalStyle = _.extend({}, {
"fill": normalColor,
"stroke": normalColor
}, options.normalStyle);
// deprecated: don't use coordX/coordY; use coord[]
if (options.coordX !== undefined) {
movablePoint.coord[0] = options.coordX;
}
if (options.coordY !== undefined) {
movablePoint.coord[1] = options.coordY;
}
var graph = movablePoint.graph;
var applySnapAndConstraints = function(coord) {
// coord should be the scaled coordinate
// move point away from edge of graph unless it's invisible or fixed
if (movablePoint.visible &&
movablePoint.bounded &&
!movablePoint.constraints.fixed) {
// can't go beyond 10 pixels from the edge
coord = graph.constrainToBounds(coord, 10);
}
var coordX = coord[0];
var coordY = coord[1];
// snap coordinates to grid
if (movablePoint.snapX !== 0) {
coordX = Math.round(coordX / movablePoint.snapX) * movablePoint.snapX;
}
if (movablePoint.snapY !== 0) {
coordY = Math.round(coordY / movablePoint.snapY) * movablePoint.snapY;
}
// snap to points around circle
if (movablePoint.constraints.fixedDistance.snapPoints) {
var mouse = graph.scalePoint(coord);
var mouseX = mouse[0];
var mouseY = mouse[1];
var snapRadians = 2 * Math.PI / movablePoint.constraints.fixedDistance.snapPoints;
var radius = movablePoint.constraints.fixedDistance.dist;
// get coordinates relative to the fixedDistance center
var centerCoord = movablePoint.constraints.fixedDistance.point;
var centerX = (centerCoord[0] - graph.range[0][0]) * graph.scale[0];
var centerY = (-centerCoord[1] + graph.range[1][1]) * graph.scale[1];
var mouseXrel = mouseX - centerX;
var mouseYrel = -mouseY + centerY;
var radians = Math.atan(mouseYrel / mouseXrel);
var outsideArcTanRange = mouseXrel < 0;
// adjust so that angles increase from 0 to 2 pi as you go around the circle
if (outsideArcTanRange) {
radians += Math.PI;
}
// perform the snap
radians = Math.round(radians / snapRadians) * snapRadians;
// convert from radians back to pixels
mouseXrel = radius * Math.cos(radians);
mouseYrel = radius * Math.sin(radians);
// convert back to coordinates relative to graphie canvas
mouseX = mouseXrel + centerX;
mouseY = - mouseYrel + centerY;
coordX = KhanUtil.roundTo(5, mouseX / graph.scale[0] + graph.range[0][0]);
coordY = KhanUtil.roundTo(5, graph.range[1][1] - mouseY / graph.scale[1]);
}
// apply any constraints on movement
var result = movablePoint.applyConstraint([coordX, coordY]);
return result;
};
// Using the passed coordinates, apply any constraints and return the closest coordinates
// that match the constraints.
movablePoint.applyConstraint = function(coord, extraConstraints, override) {
var newCoord = coord.slice();
// use the configured constraints for the point plus any passed-in constraints; use only passed-in constraints if override is set
var constraints = {};
if (override) {
$.extend(constraints, {
fixed: false,
constrainX: false,
constrainY: false,
fixedAngle: {},
fixedDistance: {}
}, extraConstraints);
} else {
$.extend(constraints, this.constraints, extraConstraints);
}
// constrain to vertical movement
if (constraints.constrainX) {
newCoord = [this.coord[0], coord[1]];
// constrain to horizontal movement
} else if (constraints.constrainY) {
newCoord = [coord[0], this.coord[1]];
// both distance and angle are constrained
} else if (typeof constraints.fixedAngle.angle === "number" && typeof constraints.fixedDistance.dist === "number") {
var vertex = constraints.fixedAngle.vertex.coord || constraints.fixedAngle.vertex;
var ref = constraints.fixedAngle.ref.coord || constraints.fixedAngle.ref;
var distPoint = constraints.fixedDistance.point.coord || constraints.fixedDistance.point;
var constrainedAngle = (constraints.fixedAngle.angle + KhanUtil.findAngle(ref, vertex)) * Math.PI / 180;
var length = constraints.fixedDistance.dist;
newCoord[0] = length * Math.cos(constrainedAngle) + distPoint[0];
newCoord[1] = length * Math.sin(constrainedAngle) + distPoint[1];
// angle is constrained
} else if (typeof constraints.fixedAngle.angle === "number") {
var vertex = constraints.fixedAngle.vertex.coord || constraints.fixedAngle.vertex;
var ref = constraints.fixedAngle.ref.coord || constraints.fixedAngle.ref;
// constrainedAngle is the angle from vertex to the point with reference to the screen
var constrainedAngle = (constraints.fixedAngle.angle + KhanUtil.findAngle(ref, vertex)) * Math.PI / 180;
// angle is the angle from vertex to the mouse with reference to the screen
var angle = KhanUtil.findAngle(coord, vertex) * Math.PI / 180;
var distance = KhanUtil.getDistance(coord, vertex);
var length = distance * Math.cos(constrainedAngle - angle);
length = length < 1.0 ? 1.0 : length;
newCoord[0] = length * Math.cos(constrainedAngle) + vertex[0];
newCoord[1] = length * Math.sin(constrainedAngle) + vertex[1];
// distance is constrained
} else if (typeof constraints.fixedDistance.dist === "number") {
var distPoint = constraints.fixedDistance.point.coord || constraints.fixedDistance.point;
var angle = KhanUtil.findAngle(coord, distPoint);
var length = constraints.fixedDistance.dist;
angle = angle * Math.PI / 180;
newCoord[0] = length * Math.cos(angle) + distPoint[0];
newCoord[1] = length * Math.sin(angle) + distPoint[1];
// point is fixed
} else if (constraints.fixed) {
newCoord = movablePoint.coord;
}
return newCoord;
};
movablePoint.coord = applySnapAndConstraints(movablePoint.coord);
var highlightScale = 2;
if (movablePoint.visible) {
graph.style(movablePoint.normalStyle, function() {
var radii = [
movablePoint.pointSize / graph.scale[0],
movablePoint.pointSize / graph.scale[1]
];
var options = {
maxScale: highlightScale
};
movablePoint.visibleShape = new WrappedEllipse(graph,
movablePoint.coord, radii, options);
movablePoint.visibleShape.attr(_.omit(movablePoint.normalStyle, "scale"));
movablePoint.visibleShape.toFront();
});
}
movablePoint.normalStyle.scale = 1;
movablePoint.highlightStyle.scale = highlightScale;
if (movablePoint.vertexLabel) {
movablePoint.labeledVertex = this.label([0, 0], "", "center", movablePoint.labelStyle);
}
movablePoint.drawLabel = function() {
if (movablePoint.vertexLabel) {
movablePoint.graph.labelVertex({
vertex: movablePoint.coord,
label: movablePoint.labeledVertex,
text: movablePoint.vertexLabel,
style: movablePoint.labelStyle
});
}
};
movablePoint.drawLabel();
movablePoint.grab = function() {
$(document).bind("vmousemove.point vmouseup.point", function(event) {
event.preventDefault();
movablePoint.dragging = true;
KhanUtil.dragging = true;
var coord = graph.getMouseCoord(event);
coord = applySnapAndConstraints(coord);
var coordX = coord[0];
var coordY = coord[1];
var mouseX;
var mouseY;
if (event.type === "vmousemove") {
var doMove = true;
// The caller has the option of adding an onMove() method to the
// movablePoint object we return as a sort of event handler
// By returning false from onMove(), the move can be vetoed,
// providing custom constraints on where the point can be moved.
// By returning array [x, y], the move can be overridden
if (_.isFunction(movablePoint.onMove)) {
var result = movablePoint.onMove(coordX, coordY);
if (result === false) {
doMove = false;
}
if (_.isArray(result)) {
coordX = result[0];
coordY = result[1];
}
}
// coord{X|Y} may have been modified by constraints or onMove handler; adjust mouse{X|Y} to match
mouseX = (coordX - graph.range[0][0]) * graph.scale[0];
mouseY = (-coordY + graph.range[1][1]) * graph.scale[1];
if (doMove) {
var point = graph.unscalePoint([mouseX, mouseY]);
movablePoint.visibleShape.moveTo(point);
movablePoint.mouseTarget.moveTo(point);
movablePoint.coord = [coordX, coordY];
movablePoint.updateLineEnds();
$(movablePoint).trigger("move");
}
movablePoint.drawLabel();
} else if (event.type === "vmouseup") {
$(document).unbind(".point");
movablePoint.dragging = false;
KhanUtil.dragging = false;