-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathpolar.js
1548 lines (1302 loc) · 47 KB
/
polar.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
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var tinycolor = require('tinycolor2');
var Registry = require('../../registry');
var Lib = require('../../lib');
var Color = require('../../components/color');
var Drawing = require('../../components/drawing');
var Plots = require('../plots');
var Axes = require('../cartesian/axes');
var doAutoRange = require('../cartesian/autorange').doAutoRange;
var dragElement = require('../../components/dragelement');
var dragBox = require('../cartesian/dragbox');
var Fx = require('../../components/fx');
var Titles = require('../../components/titles');
var prepSelect = require('../cartesian/select').prepSelect;
var clearSelect = require('../cartesian/select').clearSelect;
var setCursor = require('../../lib/setcursor');
var polygonTester = require('../../lib/polygon').tester;
var MID_SHIFT = require('../../constants/alignment').MID_SHIFT;
var _ = Lib._;
var deg2rad = Lib.deg2rad;
var rad2deg = Lib.rad2deg;
var wrap360 = Lib.wrap360;
var wrap180 = Lib.wrap180;
var setConvertAngular = require('./helpers').setConvertAngular;
var constants = require('./constants');
function Polar(gd, id) {
this.id = id;
this.gd = gd;
this._hasClipOnAxisFalse = null;
this.vangles = null;
this.radialAxisAngle = null;
this.traceHash = {};
this.layers = {};
this.clipPaths = {};
this.clipIds = {};
this.viewInitial = {};
var fullLayout = gd._fullLayout;
var clipIdBase = 'clip' + fullLayout._uid + id;
this.clipIds.forTraces = clipIdBase + '-for-traces';
this.clipPaths.forTraces = fullLayout._clips.append('clipPath')
.attr('id', this.clipIds.forTraces);
this.clipPaths.forTraces.append('path');
this.framework = fullLayout._polarlayer.append('g')
.attr('class', id);
// unfortunately, we have to keep track of some axis tick settings
// so that we don't have to call Axes.doTicksSingle with its special redraw flag
this.radialTickLayout = null;
this.angularTickLayout = null;
}
var proto = Polar.prototype;
module.exports = function createPolar(gd, id) {
return new Polar(gd, id);
};
proto.plot = function(polarCalcData, fullLayout) {
var _this = this;
var polarLayout = fullLayout[_this.id];
_this._hasClipOnAxisFalse = false;
for(var i = 0; i < polarCalcData.length; i++) {
var trace = polarCalcData[i][0].trace;
if(trace.cliponaxis === false) {
_this._hasClipOnAxisFalse = true;
break;
}
}
_this.updateLayers(fullLayout, polarLayout);
_this.updateLayout(fullLayout, polarLayout);
Plots.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout);
_this.updateFx(fullLayout, polarLayout);
};
proto.updateLayers = function(fullLayout, polarLayout) {
var _this = this;
var layers = _this.layers;
var radialLayout = polarLayout.radialaxis;
var angularLayout = polarLayout.angularaxis;
var layerNames = constants.layerNames;
var frontPlotIndex = layerNames.indexOf('frontplot');
var layerData = layerNames.slice(0, frontPlotIndex);
var isAngularAxisBelowTraces = angularLayout.layer === 'below traces';
var isRadialAxisBelowTraces = radialLayout.layer === 'below traces';
if(isAngularAxisBelowTraces) layerData.push('angular-axis');
if(isRadialAxisBelowTraces) layerData.push('radial-axis');
if(isAngularAxisBelowTraces) layerData.push('angular-line');
if(isRadialAxisBelowTraces) layerData.push('radial-line');
layerData.push('frontplot');
if(!isAngularAxisBelowTraces) layerData.push('angular-axis');
if(!isRadialAxisBelowTraces) layerData.push('radial-axis');
if(!isAngularAxisBelowTraces) layerData.push('angular-line');
if(!isRadialAxisBelowTraces) layerData.push('radial-line');
var join = _this.framework.selectAll('.polarsublayer')
.data(layerData, String);
join.enter().append('g')
.attr('class', function(d) { return 'polarsublayer ' + d;})
.each(function(d) {
var sel = layers[d] = d3.select(this);
switch(d) {
case 'frontplot':
sel.append('g').classed('scatterlayer', true);
break;
case 'backplot':
sel.append('g').classed('maplayer', true);
break;
case 'plotbg':
layers.bg = sel.append('path');
break;
case 'radial-grid':
sel.style('fill', 'none');
sel.append('g').classed('x', 1);
break;
case 'angular-grid':
sel.style('fill', 'none');
sel.append('g').classed('angular', 1);
break;
case 'radial-line':
sel.append('line').style('fill', 'none');
break;
case 'angular-line':
sel.append('path').style('fill', 'none');
break;
}
});
join.order();
};
proto.updateLayout = function(fullLayout, polarLayout) {
var _this = this;
var layers = _this.layers;
var gs = fullLayout._size;
// layout domains
var xDomain = polarLayout.domain.x;
var yDomain = polarLayout.domain.y;
// offsets from paper edge to layout domain box
_this.xOffset = gs.l + gs.w * xDomain[0];
_this.yOffset = gs.t + gs.h * (1 - yDomain[1]);
// lengths of the layout domain box
var xLength = _this.xLength = gs.w * (xDomain[1] - xDomain[0]);
var yLength = _this.yLength = gs.h * (yDomain[1] - yDomain[0]);
// sector to plot
var sector = _this.sector = polarLayout.sector;
var sectorBBox = _this.sectorBBox = computeSectorBBox(sector);
var dxSectorBBox = sectorBBox[2] - sectorBBox[0];
var dySectorBBox = sectorBBox[3] - sectorBBox[1];
// aspect ratios
var arDomain = yLength / xLength;
var arSector = Math.abs(dySectorBBox / dxSectorBBox);
// actual lengths and domains of subplot box
var xLength2, yLength2;
var xDomain2, yDomain2;
var gap;
if(arDomain > arSector) {
xLength2 = xLength;
yLength2 = xLength * arSector;
gap = (yLength - yLength2) / gs.h / 2;
xDomain2 = [xDomain[0], xDomain[1]];
yDomain2 = [yDomain[0] + gap, yDomain[1] - gap];
} else {
xLength2 = yLength / arSector;
yLength2 = yLength;
gap = (xLength - xLength2) / gs.w / 2;
xDomain2 = [xDomain[0] + gap, xDomain[1] - gap];
yDomain2 = [yDomain[0], yDomain[1]];
}
_this.xLength2 = xLength2;
_this.yLength2 = yLength2;
_this.xDomain2 = xDomain2;
_this.yDomain2 = yDomain2;
// actual offsets from paper edge to the subplot box top-left corner
var xOffset2 = _this.xOffset2 = gs.l + gs.w * xDomain2[0];
var yOffset2 = _this.yOffset2 = gs.t + gs.h * (1 - yDomain2[1]);
// circle radius in px
var radius = _this.radius = xLength2 / dxSectorBBox;
// circle center position in px
var cx = _this.cx = xOffset2 - radius * sectorBBox[0];
var cy = _this.cy = yOffset2 + radius * sectorBBox[3];
// circle center in the coordinate system of plot area
var cxx = _this.cxx = cx - xOffset2;
var cyy = _this.cyy = cy - yOffset2;
var mockOpts = {
// to get _boundingBox computation right when showticklabels is false
anchor: 'free',
position: 0,
// dummy truthy value to make Axes.doTicksSingle draw the grid
_counteraxis: true,
// don't use automargins routine for labels
automargin: false
};
_this.radialAxis = Lib.extendFlat({}, polarLayout.radialaxis, mockOpts, {
_axislayer: layers['radial-axis'],
_gridlayer: layers['radial-grid'],
// make this an 'x' axis to make positioning (especially rotation) easier
_id: 'x',
_pos: 0,
// convert to 'x' axis equivalent
side: {
counterclockwise: 'top',
clockwise: 'bottom'
}[polarLayout.radialaxis.side],
// spans length 1 radius
domain: [0, radius / gs.w]
});
_this.angularAxis = Lib.extendFlat({}, polarLayout.angularaxis, mockOpts, {
_axislayer: layers['angular-axis'],
_gridlayer: layers['angular-grid'],
// angular axes need *special* logic
_id: 'angular',
_pos: 0,
side: 'right',
// to get auto nticks right
domain: [0, Math.PI],
// don't pass through autorange logic
autorange: false
});
_this.doAutoRange(fullLayout, polarLayout);
// N.B. this sets _this.vangles
_this.updateAngularAxis(fullLayout, polarLayout);
// N.B. this sets _this.radialAxisAngle
_this.updateRadialAxis(fullLayout, polarLayout);
_this.updateRadialAxisTitle(fullLayout, polarLayout);
var radialRange = _this.radialAxis.range;
var rSpan = radialRange[1] - radialRange[0];
var xaxis = _this.xaxis = {
type: 'linear',
_id: 'x',
range: [sectorBBox[0] * rSpan, sectorBBox[2] * rSpan],
domain: xDomain2
};
Axes.setConvert(xaxis, fullLayout);
xaxis.setScale();
var yaxis = _this.yaxis = {
type: 'linear',
_id: 'y',
range: [sectorBBox[1] * rSpan, sectorBBox[3] * rSpan],
domain: yDomain2
};
Axes.setConvert(yaxis, fullLayout);
yaxis.setScale();
xaxis.isPtWithinRange = function(d) { return _this.isPtWithinSector(d); };
yaxis.isPtWithinRange = function() { return true; };
_this.clipPaths.forTraces.select('path')
.attr('d', pathSectorClosed(radius, sector, _this.vangles))
.attr('transform', strTranslate(cxx, cyy));
layers.frontplot
.attr('transform', strTranslate(xOffset2, yOffset2))
.call(Drawing.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.forTraces);
layers.bg
.attr('d', pathSectorClosed(radius, sector, _this.vangles))
.attr('transform', strTranslate(cx, cy))
.call(Color.fill, polarLayout.bgcolor);
// remove crispEdges - all the off-square angles in polar plots
// make these counterproductive.
_this.framework.selectAll('.crisp').classed('crisp', 0);
};
proto.doAutoRange = function(fullLayout, polarLayout) {
var radialLayout = polarLayout.radialaxis;
var ax = this.radialAxis;
setScale(ax, radialLayout, fullLayout);
doAutoRange(ax);
radialLayout.range = ax.range.slice();
radialLayout._input.range = ax.range.slice();
};
proto.updateRadialAxis = function(fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var cx = _this.cx;
var cy = _this.cy;
var radialLayout = polarLayout.radialaxis;
var sector = polarLayout.sector;
var a0 = wrap360(sector[0]);
var ax = _this.radialAxis;
_this.fillViewInitialKey('radialaxis.angle', radialLayout.angle);
_this.fillViewInitialKey('radialaxis.range', ax.range.slice());
// rotate auto tick labels by 180 if in quadrant II and III to make them
// readable from left-to-right
//
// TODO try moving deeper in doTicksSingle for better results?
if(ax.tickangle === 'auto' && (a0 > 90 && a0 <= 270)) {
ax.tickangle = 180;
}
// easier to set rotate angle with custom translate function
ax._transfn = function(d) {
return 'translate(' + ax.l2p(d.x) + ',0)';
};
// set special grid path function
ax._gridpath = function(d) {
var r = ax.r2p(d.x);
return pathSector(r, sector, _this.vangles);
};
var newTickLayout = strTickLayout(radialLayout);
if(_this.radialTickLayout !== newTickLayout) {
layers['radial-axis'].selectAll('.xtick').remove();
_this.radialTickLayout = newTickLayout;
}
Axes.doTicksSingle(gd, ax, true);
// stash 'actual' radial axis angle for drag handlers (in degrees)
var angle = _this.radialAxisAngle = _this.vangles ?
rad2deg(snapToVertexAngle(deg2rad(radialLayout.angle), _this.vangles)) :
radialLayout.angle;
var trans = strTranslate(cx, cy) + strRotate(-angle);
updateElement(layers['radial-axis'], radialLayout.showticklabels || radialLayout.ticks, {
transform: trans
});
// move all grid paths to about circle center,
// undo individual grid lines translations
updateElement(layers['radial-grid'], radialLayout.showgrid, {
transform: strTranslate(cx, cy)
})
.selectAll('path').attr('transform', null);
updateElement(layers['radial-line'].select('line'), radialLayout.showline, {
x1: 0,
y1: 0,
x2: radius,
y2: 0,
transform: trans
})
.attr('stroke-width', radialLayout.linewidth)
.call(Color.stroke, radialLayout.linecolor);
};
proto.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) {
var _this = this;
var gd = _this.gd;
var radius = _this.radius;
var cx = _this.cx;
var cy = _this.cy;
var radialLayout = polarLayout.radialaxis;
var titleClass = _this.id + 'title';
var angle = _angle !== undefined ? _angle : _this.radialAxisAngle;
var angleRad = deg2rad(angle);
var cosa = Math.cos(angleRad);
var sina = Math.sin(angleRad);
var pad = 0;
if(radialLayout.title) {
var h = Drawing.bBox(_this.layers['radial-axis'].node()).height;
var ts = radialLayout.titlefont.size;
pad = radialLayout.side === 'counterclockwise' ?
-h - ts * 0.4 :
h + ts * 0.8;
}
_this.layers['radial-axis-title'] = Titles.draw(gd, titleClass, {
propContainer: radialLayout,
propName: _this.id + '.radialaxis.title',
placeholder: _(gd, 'Click to enter radial axis title'),
attributes: {
x: cx + (radius / 2) * cosa + pad * sina,
y: cy - (radius / 2) * sina + pad * cosa,
'text-anchor': 'middle'
},
transform: {rotate: -angle}
});
};
proto.updateAngularAxis = function(fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var cx = _this.cx;
var cy = _this.cy;
var angularLayout = polarLayout.angularaxis;
var sector = polarLayout.sector;
var sectorInRad = sector.map(deg2rad);
var ax = _this.angularAxis;
_this.fillViewInitialKey('angularaxis.rotation', angularLayout.rotation);
// wrapper around c2rad from setConvertAngular
// note that linear ranges are always set in degrees for Axes.doTicksSingle
function c2rad(d) {
return ax.c2rad(d.x, 'degrees');
}
// (x,y) at max radius
function rad2xy(rad) {
return [radius * Math.cos(rad), radius * Math.sin(rad)];
}
// Set the angular range in degrees to make auto-tick computation cleaner,
// changing rotation/direction should not affect the angular tick labels.
if(ax.type === 'linear') {
if(isFullCircle(sector)) {
ax.range = sector.slice();
} else {
ax.range = sectorInRad.map(ax.unTransformRad).map(rad2deg);
}
// run rad2deg on tick0 and ditck for thetaunit: 'radians' axes
if(ax.thetaunit === 'radians') {
ax.tick0 = rad2deg(ax.tick0);
ax.dtick = rad2deg(ax.dtick);
}
}
// Use tickval filter for category axes instead of tweaking
// the range w.r.t sector, so that sectors that cross 360 can
// show all their ticks.
else if(ax.type === 'category') {
var period = angularLayout.period ?
Math.max(angularLayout.period, angularLayout._categories.length) :
angularLayout._categories.length;
ax.range = [0, period];
ax._tickFilter = function(d) { return isAngleInSector(c2rad(d), sector); };
}
setScale(ax, angularLayout, fullLayout);
ax._transfn = function(d) {
var rad = c2rad(d);
var xy = rad2xy(rad);
var out = strTranslate(cx + xy[0], cy - xy[1]);
// must also rotate ticks, but don't rotate labels and grid lines
var sel = d3.select(this);
if(sel && sel.node() && sel.classed('ticks')) {
out += strRotate(-rad2deg(rad));
}
return out;
};
ax._gridpath = function(d) {
var rad = c2rad(d);
var xy = rad2xy(rad);
return 'M0,0L' + (-xy[0]) + ',' + xy[1];
};
var offset4fontsize = (angularLayout.ticks !== 'outside' ? 0.7 : 0.5);
ax._labelx = function(d) {
var rad = c2rad(d);
var labelStandoff = ax._labelStandoff;
var pad = ax._pad;
var offset4tx = signSin(rad) === 0 ?
0 :
Math.cos(rad) * (labelStandoff + pad + offset4fontsize * d.fontSize);
var offset4tick = signCos(rad) * (d.dx + labelStandoff + pad);
return offset4tx + offset4tick;
};
ax._labely = function(d) {
var rad = c2rad(d);
var labelStandoff = ax._labelStandoff;
var labelShift = ax._labelShift;
var pad = ax._pad;
var offset4tx = d.dy + d.fontSize * MID_SHIFT - labelShift;
var offset4tick = -Math.sin(rad) * (labelStandoff + pad + offset4fontsize * d.fontSize);
return offset4tx + offset4tick;
};
ax._labelanchor = function(angle, d) {
var rad = c2rad(d);
return signSin(rad) === 0 ?
(signCos(rad) > 0 ? 'start' : 'end') :
'middle';
};
var newTickLayout = strTickLayout(angularLayout);
if(_this.angularTickLayout !== newTickLayout) {
layers['angular-axis'].selectAll('.angulartick').remove();
_this.angularTickLayout = newTickLayout;
}
Axes.doTicksSingle(gd, ax, true);
// angle of polygon vertices in radians (null means circles)
// TODO what to do when ax.period > ax._categories ??
var vangles;
if(polarLayout.gridshape === 'linear') {
vangles = ax._vals.map(c2rad);
// ax._vals should be always ordered, make them
// always turn counterclockwise for convenience here
if(angleDelta(vangles[0], vangles[1]) < 0) {
vangles = vangles.slice().reverse();
}
} else {
vangles = null;
}
_this.vangles = vangles;
updateElement(layers['angular-line'].select('path'), angularLayout.showline, {
d: pathSectorClosed(radius, sector, vangles),
transform: strTranslate(cx, cy)
})
.attr('stroke-width', angularLayout.linewidth)
.call(Color.stroke, angularLayout.linecolor);
};
proto.updateFx = function(fullLayout, polarLayout) {
if(!this.gd._context.staticPlot) {
this.updateAngularDrag(fullLayout, polarLayout);
this.updateRadialDrag(fullLayout, polarLayout);
this.updateMainDrag(fullLayout, polarLayout);
}
};
proto.updateMainDrag = function(fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var zoomlayer = fullLayout._zoomlayer;
var MINZOOM = constants.MINZOOM;
var OFFEDGE = constants.OFFEDGE;
var radius = _this.radius;
var cx = _this.cx;
var cy = _this.cy;
var cxx = _this.cxx;
var cyy = _this.cyy;
var sector = polarLayout.sector;
var vangles = _this.vangles;
var chw = constants.cornerHalfWidth;
var chl = constants.cornerLen / 2;
var mainDrag = dragBox.makeDragger(layers, 'path', 'maindrag', 'crosshair');
d3.select(mainDrag)
.attr('d', pathSectorClosed(radius, sector, vangles))
.attr('transform', strTranslate(cx, cy));
var dragOpts = {
element: mainDrag,
gd: gd,
subplot: _this.id,
plotinfo: {
xaxis: _this.xaxis,
yaxis: _this.yaxis
},
xaxes: [_this.xaxis],
yaxes: [_this.yaxis]
};
// mouse px position at drag start (0), move (1)
var x0, y0;
// radial distance from circle center at drag start (0), move (1)
var r0, r1;
// zoombox persistent quantities
var path0, dimmed, lum;
// zoombox, corners elements
var zb, corners;
function norm(x, y) {
return Math.sqrt(x * x + y * y);
}
function xy2r(x, y) {
return norm(x - cxx, y - cyy);
}
function xy2a(x, y) {
return Math.atan2(cyy - y, x - cxx);
}
function ra2xy(r, a) {
return [r * Math.cos(a), r * Math.sin(-a)];
}
function _pathSectorClosed(r) {
return pathSectorClosed(r, sector, vangles);
}
function pathCorner(r, a) {
if(r === 0) return _pathSectorClosed(2 * chw);
var da = chl / r;
var am = a - da;
var ap = a + da;
var rb = Math.max(0, Math.min(r, radius));
var rm = rb - chw;
var rp = rb + chw;
return 'M' + ra2xy(rm, am) +
'A' + [rm, rm] + ' 0,0,0 ' + ra2xy(rm, ap) +
'L' + ra2xy(rp, ap) +
'A' + [rp, rp] + ' 0,0,1 ' + ra2xy(rp, am) +
'Z';
}
// (x,y) is the pt at middle of the va0 <-> va1 edge
//
// ... we could eventually add another mode for cursor
// angles 'close to' enough to a particular vertex.
function pathCornerForPolygons(r, va0, va1) {
if(r === 0) return _pathSectorClosed(2 * chw);
var xy0 = ra2xy(r, va0);
var xy1 = ra2xy(r, va1);
var x = (xy0[0] + xy1[0]) / 2;
var y = (xy0[1] + xy1[1]) / 2;
var innerPts, outerPts;
if(x && y) {
var m = y / x;
var mperp = -1 / m;
var midPts = findXYatLength(chw, m, x, y);
innerPts = findXYatLength(chl, mperp, midPts[0][0], midPts[0][1]);
outerPts = findXYatLength(chl, mperp, midPts[1][0], midPts[1][1]);
} else {
// horizontal / vertical
innerPts = [[x - chl, y - chw], [x + chl, y - chw]];
outerPts = [[x - chl, y + chw], [x + chl, y + chw]];
}
return 'M' + innerPts.join('L') +
'L' + outerPts.reverse().join('L') + 'Z';
}
function zoomPrep() {
r0 = null;
r1 = null;
path0 = _pathSectorClosed(radius);
dimmed = false;
var polarLayoutNow = gd._fullLayout[_this.id];
lum = tinycolor(polarLayoutNow.bgcolor).getLuminance();
zb = dragBox.makeZoombox(zoomlayer, lum, cx, cy, path0);
zb.attr('fill-rule', 'evenodd');
corners = dragBox.makeCorners(zoomlayer, cx, cy);
clearSelect(zoomlayer);
}
// N.B. this sets scoped 'r0' and 'r1'
// return true if 'valid' zoom distance, false otherwise
function clampAndSetR0R1(rr0, rr1) {
rr1 = Math.min(rr1, radius);
// starting or ending drag near center (outer edge),
// clamps radial distance at origin (at r=radius)
if(rr0 < OFFEDGE) rr0 = 0;
else if((radius - rr0) < OFFEDGE) rr0 = radius;
else if(rr1 < OFFEDGE) rr1 = 0;
else if((radius - rr1) < OFFEDGE) rr1 = radius;
// make sure r0 < r1,
// to get correct fill pattern in path1 below
if(Math.abs(rr1 - rr0) > MINZOOM) {
if(rr0 < rr1) {
r0 = rr0;
r1 = rr1;
} else {
r0 = rr1;
r1 = rr0;
}
return true;
} else {
r0 = null;
r1 = null;
return false;
}
}
function applyZoomMove(path1, cpath) {
path1 = path1 || path0;
cpath = cpath || 'M0,0Z';
zb.attr('d', path1);
corners.attr('d', cpath);
dragBox.transitionZoombox(zb, corners, dimmed, lum);
dimmed = true;
}
function zoomMove(dx, dy) {
var x1 = x0 + dx;
var y1 = y0 + dy;
var rr0 = xy2r(x0, y0);
var rr1 = Math.min(xy2r(x1, y1), radius);
var a0 = xy2a(x0, y0);
var path1;
var cpath;
if(clampAndSetR0R1(rr0, rr1)) {
path1 = path0 + _pathSectorClosed(r1) + _pathSectorClosed(r0);
// keep 'starting' angle
cpath = pathCorner(r0, a0) + pathCorner(r1, a0);
}
applyZoomMove(path1, cpath);
}
function findEnclosingVertexAngles(a) {
var cycleIndex = makeCycleIndexFn(vangles.length);
var i0 = findIndexOfMin(vangles, function(v) {
if(!isAngleInSector(v, sector)) return Infinity;
var adelta = angleDelta(v, a);
return adelta > 0 ? adelta : Infinity;
});
return [vangles[i0], vangles[cycleIndex(i0 + 1)]];
}
function findPolygonRadius(x, y, va0, va1) {
var xy = findIntersectionXY(va0, va1, va0, [x - cxx, cyy - y]);
return norm(xy[0], xy[1]);
}
function zoomMoveForPolygons(dx, dy) {
var x1 = x0 + dx;
var y1 = y0 + dy;
var a0 = xy2a(x0, y0);
var a1 = xy2a(x1, y1);
var vangles0 = findEnclosingVertexAngles(a0);
var vangles1 = findEnclosingVertexAngles(a1);
var rr0 = findPolygonRadius(x0, y0, vangles0[0], vangles0[1]);
var rr1 = Math.min(findPolygonRadius(x1, y1, vangles1[0], vangles1[1]), radius);
var path1;
var cpath;
if(clampAndSetR0R1(rr0, rr1)) {
path1 = path0 + _pathSectorClosed(r1) + _pathSectorClosed(r0);
// keep 'starting' angle here too
cpath = [
pathCornerForPolygons(r0, vangles0[0], vangles0[1]),
pathCornerForPolygons(r1, vangles0[0], vangles0[1])
].join(' ');
}
applyZoomMove(path1, cpath);
}
function zoomDone() {
dragBox.removeZoombox(gd);
if(r0 === null || r1 === null) return;
dragBox.showDoubleClickNotifier(gd);
var radialAxis = _this.radialAxis;
var radialRange = radialAxis.range;
var drange = radialRange[1] - radialRange[0];
var updateObj = {};
updateObj[_this.id + '.radialaxis.range'] = [
radialRange[0] + r0 * drange / radius,
radialRange[0] + r1 * drange / radius
];
Registry.call('relayout', gd, updateObj);
}
dragOpts.prepFn = function(evt, startX, startY) {
var dragModeNow = gd._fullLayout.dragmode;
var bbox = mainDrag.getBoundingClientRect();
x0 = startX - bbox.left;
y0 = startY - bbox.top;
switch(dragModeNow) {
case 'zoom':
if(vangles) {
dragOpts.moveFn = zoomMoveForPolygons;
} else {
dragOpts.moveFn = zoomMove;
}
dragOpts.doneFn = zoomDone;
zoomPrep(evt, startX, startY);
break;
case 'select':
case 'lasso':
prepSelect(evt, startX, startY, dragOpts, dragModeNow);
break;
}
};
dragOpts.clickFn = function(numClicks, evt) {
dragBox.removeZoombox(gd);
// TODO double once vs twice logic (autorange vs fixed range)
if(numClicks === 2) {
var updateObj = {};
for(var k in _this.viewInitial) {
updateObj[_this.id + '.' + k] = _this.viewInitial[k];
}
gd.emit('plotly_doubleclick', null);
Registry.call('relayout', gd, updateObj);
}
Fx.click(gd, evt, _this.id);
};
mainDrag.onmousemove = function(evt) {
Fx.hover(gd, evt, _this.id);
gd._fullLayout._lasthover = mainDrag;
gd._fullLayout._hoversubplot = _this.id;
};
mainDrag.onmouseout = function(evt) {
if(gd._dragging) return;
dragElement.unhover(gd, evt);
};
dragElement.init(dragOpts);
};
proto.updateRadialDrag = function(fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var cx = _this.cx;
var cy = _this.cy;
var radialAxis = _this.radialAxis;
var radialLayout = polarLayout.radialaxis;
var angle0 = deg2rad(_this.radialAxisAngle);
var range0 = radialAxis.range.slice();
var drange = range0[1] - range0[0];
var bl = constants.radialDragBoxSize;
var bl2 = bl / 2;
if(!radialLayout.visible) return;
var radialDrag = dragBox.makeRectDragger(layers, 'radialdrag', 'crosshair', -bl2, -bl2, bl, bl);
var dragOpts = {element: radialDrag, gd: gd};
var tx = cx + (radius + bl2) * Math.cos(angle0);
var ty = cy - (radius + bl2) * Math.sin(angle0);
d3.select(radialDrag)
.attr('transform', strTranslate(tx, ty));
// move function (either rotate or re-range flavor)
var moveFn2;
// rotate angle on done
var angle1;
// re-range range[1] on done
var rng1;
function moveFn(dx, dy) {
if(moveFn2) {
moveFn2(dx, dy);
} else {
var dvec = [dx, -dy];
var rvec = [Math.cos(angle0), Math.sin(angle0)];
var comp = Math.abs(Lib.dot(dvec, rvec) / Math.sqrt(Lib.dot(dvec, dvec)));
// mostly perpendicular motions rotate,
// mostly parallel motions re-range
if(!isNaN(comp)) {
moveFn2 = comp < 0.5 ? rotateMove : rerangeMove;
}
}
}
function doneFn() {
if(angle1 !== null) {
Registry.call('relayout', gd, _this.id + '.radialaxis.angle', angle1);
} else if(rng1 !== null) {
Registry.call('relayout', gd, _this.id + '.radialaxis.range[1]', rng1);
}
}
function rotateMove(dx, dy) {
var x1 = tx + dx;
var y1 = ty + dy;
angle1 = Math.atan2(cy - y1, x1 - cx);
if(_this.vangles) angle1 = snapToVertexAngle(angle1, _this.vangles);
angle1 = rad2deg(angle1);
var transform = strTranslate(cx, cy) + strRotate(-angle1);
layers['radial-axis'].attr('transform', transform);
layers['radial-line'].select('line').attr('transform', transform);
var fullLayoutNow = _this.gd._fullLayout;
var polarLayoutNow = fullLayoutNow[_this.id];
_this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, angle1);
}
function rerangeMove(dx, dy) {
// project (dx, dy) unto unit radial axis vector
var dr = Lib.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]);
var rprime = range0[1] - drange * dr / radius * 0.75;
// make sure new range[1] does not change the range[0] -> range[1] sign
if((drange > 0) !== (rprime > range0[0])) return;
rng1 = radialAxis.range[1] = rprime;
Axes.doTicksSingle(gd, _this.radialAxis, true);
layers['radial-grid']
.attr('transform', strTranslate(cx, cy))
.selectAll('path').attr('transform', null);
var rSpan = rng1 - range0[0];
var sectorBBox = _this.sectorBBox;
_this.xaxis.range = [sectorBBox[0] * rSpan, sectorBBox[2] * rSpan];
_this.yaxis.range = [sectorBBox[1] * rSpan, sectorBBox[3] * rSpan];
_this.xaxis.setScale();
_this.yaxis.setScale();
for(var k in _this.traceHash) {
var moduleCalcData = _this.traceHash[k];
var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
var _module = moduleCalcData[0][0].trace._module;
var polarLayoutNow = gd._fullLayout[_this.id];
_module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
if(!Registry.traceIs(k, 'gl')) {
for(var i = 0; i < moduleCalcDataVisible.length; i++) {
_module.style(gd, moduleCalcDataVisible[i]);
}
}
}
}
dragOpts.prepFn = function() {
moveFn2 = null;
angle1 = null;
rng1 = null;
dragOpts.moveFn = moveFn;
dragOpts.doneFn = doneFn;
clearSelect(fullLayout._zoomlayer);
};
dragOpts.clampFn = function(dx, dy) {
if(Math.sqrt(dx * dx + dy * dy) < constants.MINDRAG) {
dx = 0;
dy = 0;
}
return [dx, dy];
};
dragElement.init(dragOpts);
};
proto.updateAngularDrag = function(fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var cx = _this.cx;
var cy = _this.cy;
var cxx = _this.cxx;
var cyy = _this.cyy;