-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathgraph_interact.js
1347 lines (1165 loc) · 47.3 KB
/
graph_interact.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-2016, 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 isNumeric = require('fast-isnumeric');
var Lib = require('../../lib');
var Events = require('../../lib/events');
var svgTextUtils = require('../../lib/svg_text_utils');
var Color = require('../../components/color');
var Drawing = require('../../components/drawing');
var dragElement = require('../../components/dragelement');
var Axes = require('./axes');
var constants = require('./constants');
var dragBox = require('./dragbox');
var fx = module.exports = {};
// TODO remove this in version 2.0
// copy on Fx for backward compatible
fx.unhover = dragElement.unhover;
fx.layoutAttributes = {
dragmode: {
valType: 'enumerated',
role: 'info',
values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'],
dflt: 'zoom',
description: [
'Determines the mode of drag interactions.',
'*select* and *lasso* apply only to scatter traces with',
'markers or text. *orbit* and *turntable* apply only to',
'3D scenes.'
].join(' ')
},
hovermode: {
valType: 'enumerated',
role: 'info',
values: ['x', 'y', 'closest', false],
description: 'Determines the mode of hover interactions.'
}
};
fx.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, fx.layoutAttributes, attr, dflt);
}
coerce('dragmode');
var hovermodeDflt;
if(layoutOut._has('cartesian')) {
// flag for 'horizontal' plots:
// determines the state of the mode bar 'compare' hovermode button
var isHoriz = layoutOut._isHoriz = fx.isHoriz(fullData);
hovermodeDflt = isHoriz ? 'y' : 'x';
}
else hovermodeDflt = 'closest';
coerce('hovermode', hovermodeDflt);
};
fx.isHoriz = function(fullData) {
var isHoriz = true;
for(var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if(trace.orientation !== 'h') {
isHoriz = false;
break;
}
}
return isHoriz;
};
fx.init = function(gd) {
var fullLayout = gd._fullLayout;
if(!fullLayout._has('cartesian') || gd._context.staticPlot) return;
var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
// sort overlays last, then by x axis number, then y axis number
if((fullLayout._plots[a].mainplot && true) ===
(fullLayout._plots[b].mainplot && true)) {
var aParts = a.split('y'),
bParts = b.split('y');
return (aParts[0] === bParts[0]) ?
(Number(aParts[1] || 1) - Number(bParts[1] || 1)) :
(Number(aParts[0] || 1) - Number(bParts[0] || 1));
}
return fullLayout._plots[a].mainplot ? 1 : -1;
});
subplots.forEach(function(subplot) {
var plotinfo = fullLayout._plots[subplot];
if(!fullLayout._has('cartesian')) return;
var xa = plotinfo.x(),
ya = plotinfo.y(),
// the y position of the main x axis line
y0 = (xa._linepositions[subplot] || [])[3],
// the x position of the main y axis line
x0 = (ya._linepositions[subplot] || [])[3];
var DRAGGERSIZE = constants.DRAGGERSIZE;
if(isNumeric(y0) && xa.side === 'top') y0 -= DRAGGERSIZE;
if(isNumeric(x0) && ya.side !== 'right') x0 -= DRAGGERSIZE;
// main and corner draggers need not be repeated for
// overlaid subplots - these draggers drag them all
if(!plotinfo.mainplot) {
// main dragger goes over the grids and data, so we use its
// mousemove events for all data hover effects
var maindrag = dragBox(gd, plotinfo, 0, 0,
xa._length, ya._length, 'ns', 'ew');
maindrag.onmousemove = function(evt) {
fx.hover(gd, evt, subplot);
fullLayout._lasthover = maindrag;
fullLayout._hoversubplot = subplot;
};
/*
* IMPORTANT:
* We must check for the presence of the drag cover here.
* If we don't, a 'mouseout' event is triggered on the
* maindrag before each 'click' event, which has the effect
* of clearing the hoverdata; thus, cancelling the click event.
*/
maindrag.onmouseout = function(evt) {
if(gd._dragging) return;
dragElement.unhover(gd, evt);
};
maindrag.onclick = function(evt) {
fx.click(gd, evt);
};
// corner draggers
dragBox(gd, plotinfo, -DRAGGERSIZE, -DRAGGERSIZE,
DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
dragBox(gd, plotinfo, xa._length, -DRAGGERSIZE,
DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
dragBox(gd, plotinfo, -DRAGGERSIZE, ya._length,
DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
dragBox(gd, plotinfo, xa._length, ya._length,
DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
}
// x axis draggers - if you have overlaid plots,
// these drag each axis separately
if(isNumeric(y0)) {
if(xa.anchor === 'free') y0 -= fullLayout._size.h * (1 - ya.domain[1]);
dragBox(gd, plotinfo, xa._length * 0.1, y0,
xa._length * 0.8, DRAGGERSIZE, '', 'ew');
dragBox(gd, plotinfo, 0, y0,
xa._length * 0.1, DRAGGERSIZE, '', 'w');
dragBox(gd, plotinfo, xa._length * 0.9, y0,
xa._length * 0.1, DRAGGERSIZE, '', 'e');
}
// y axis draggers
if(isNumeric(x0)) {
if(ya.anchor === 'free') x0 -= fullLayout._size.w * xa.domain[0];
dragBox(gd, plotinfo, x0, ya._length * 0.1,
DRAGGERSIZE, ya._length * 0.8, 'ns', '');
dragBox(gd, plotinfo, x0, ya._length * 0.9,
DRAGGERSIZE, ya._length * 0.1, 's', '');
dragBox(gd, plotinfo, x0, 0,
DRAGGERSIZE, ya._length * 0.1, 'n', '');
}
});
// In case you mousemove over some hovertext, send it to fx.hover too
// we do this so that we can put the hover text in front of everything,
// but still be able to interact with everything as if it isn't there
var hoverLayer = fullLayout._hoverlayer.node();
hoverLayer.onmousemove = function(evt) {
evt.target = fullLayout._lasthover;
fx.hover(gd, evt, fullLayout._hoversubplot);
};
hoverLayer.onclick = function(evt) {
evt.target = fullLayout._lasthover;
fx.click(gd, evt);
};
// also delegate mousedowns... TODO: does this actually work?
hoverLayer.onmousedown = function(evt) {
fullLayout._lasthover.onmousedown(evt);
};
};
// hover labels for multiple horizontal bars get tilted by some angle,
// then need to be offset differently if they overlap
var YANGLE = constants.YANGLE,
YA_RADIANS = Math.PI * YANGLE / 180,
// expansion of projected height
YFACTOR = 1 / Math.sin(YA_RADIANS),
// to make the appropriate post-rotation x offset,
// you need both x and y offsets
YSHIFTX = Math.cos(YA_RADIANS),
YSHIFTY = Math.sin(YA_RADIANS);
// convenience functions for mapping all relevant axes
function flat(subplots, v) {
var out = [];
for(var i = subplots.length; i > 0; i--) out.push(v);
return out;
}
function p2c(axArray, v) {
var out = [];
for(var i = 0; i < axArray.length; i++) out.push(axArray[i].p2c(v));
return out;
}
function quadrature(dx, dy) {
return function(di) {
var x = dx(di),
y = dy(di);
return Math.sqrt(x * x + y * y);
};
}
// size and display constants for hover text
var HOVERARROWSIZE = constants.HOVERARROWSIZE,
HOVERTEXTPAD = constants.HOVERTEXTPAD,
HOVERFONTSIZE = constants.HOVERFONTSIZE,
HOVERFONT = constants.HOVERFONT;
// fx.hover: highlight data on hover
// evt can be a mousemove event, or an object with data about what points
// to hover on
// {xpx,ypx[,hovermode]} - pixel locations from top left
// (with optional overriding hovermode)
// {xval,yval[,hovermode]} - data values
// [{curveNumber,(pointNumber|xval and/or yval)}] -
// array of specific points to highlight
// pointNumber is a single integer if gd.data[curveNumber] is 1D,
// or a two-element array if it's 2D
// xval and yval are data values,
// 1D data may specify either or both,
// 2D data must specify both
// subplot is an id string (default "xy")
// makes use of gl.hovermode, which can be:
// x (find the points with the closest x values, ie a column),
// closest (find the single closest point)
// internally there are two more that occasionally get used:
// y (pick out a row - only used for multiple horizontal bar charts)
// array (used when the user specifies an explicit
// array of points to hover on)
//
// We wrap the hovers in a timer, to limit their frequency.
// The actual rendering is done by private functions
// hover() and unhover().
fx.hover = function(gd, evt, subplot) {
if(typeof gd === 'string') gd = document.getElementById(gd);
if(gd._lastHoverTime === undefined) gd._lastHoverTime = 0;
// If we have an update queued, discard it now
if(gd._hoverTimer !== undefined) {
clearTimeout(gd._hoverTimer);
gd._hoverTimer = undefined;
}
// Is it more than 100ms since the last update? If so, force
// an update now (synchronously) and exit
if(Date.now() > gd._lastHoverTime + constants.HOVERMINTIME) {
hover(gd, evt, subplot);
gd._lastHoverTime = Date.now();
return;
}
// Queue up the next hover for 100ms from now (if no further events)
gd._hoverTimer = setTimeout(function() {
hover(gd, evt, subplot);
gd._lastHoverTime = Date.now();
gd._hoverTimer = undefined;
}, constants.HOVERMINTIME);
};
// The actual implementation is here:
function hover(gd, evt, subplot) {
if(subplot === 'pie') {
gd.emit('plotly_hover', {
points: [evt]
});
return;
}
if(!subplot) subplot = 'xy';
// if the user passed in an array of subplots,
// use those instead of finding overlayed plots
var subplots = Array.isArray(subplot) ? subplot : [subplot];
var fullLayout = gd._fullLayout,
plots = fullLayout._plots || [],
plotinfo = plots[subplot];
// list of all overlaid subplots to look at
if(plotinfo) {
var overlayedSubplots = plotinfo.overlays.map(function(pi) {
return pi.id;
});
subplots = subplots.concat(overlayedSubplots);
}
var len = subplots.length,
xaArray = new Array(len),
yaArray = new Array(len);
for(var i = 0; i < len; i++) {
var spId = subplots[i];
// 'cartesian' case
var plotObj = plots[spId];
if(plotObj) {
// TODO make sure that fullLayout_plots axis refs
// get updated properly so that we don't have
// to use Axes.getFromId in general.
xaArray[i] = Axes.getFromId(gd, plotObj.xaxis._id);
yaArray[i] = Axes.getFromId(gd, plotObj.yaxis._id);
continue;
}
// other subplot types
var _subplot = fullLayout[spId]._subplot;
xaArray[i] = _subplot.xaxis;
yaArray[i] = _subplot.yaxis;
}
var hovermode = evt.hovermode || fullLayout.hovermode;
if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata ||
gd.querySelector('.zoombox') || gd._dragging) {
return dragElement.unhoverRaw(gd, evt);
}
// hoverData: the set of candidate points we've found to highlight
var hoverData = [],
// searchData: the data to search in. Mostly this is just a copy of
// gd.calcdata, filtered to the subplot and overlays we're on
// but if a point array is supplied it will be a mapping
// of indicated curves
searchData = [],
// [x|y]valArray: the axis values of the hover event
// mapped onto each of the currently selected overlaid subplots
xvalArray,
yvalArray,
// used in loops
itemnum,
curvenum,
cd,
trace,
subploti,
mode,
xval,
yval,
pointData,
closedataPreviousLength;
// Figure out what we're hovering on:
// mouse location or user-supplied data
if(Array.isArray(evt)) {
// user specified an array of points to highlight
hovermode = 'array';
for(itemnum = 0; itemnum < evt.length; itemnum++) {
cd = gd.calcdata[evt[itemnum].curveNumber||0];
if(cd[0].trace.hoverinfo !== 'skip') {
searchData.push(cd);
}
}
}
else {
for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) {
cd = gd.calcdata[curvenum];
trace = cd[0].trace;
if(trace.hoverinfo !== 'skip' && subplots.indexOf(getSubplot(trace)) !== -1) {
searchData.push(cd);
}
}
// [x|y]px: the pixels (from top left) of the mouse location
// on the currently selected plot area
var xpx, ypx;
// mouse event? ie is there a target element with
// clientX and clientY values?
if(evt.target && ('clientX' in evt) && ('clientY' in evt)) {
// fire the beforehover event and quit if it returns false
// note that we're only calling this on real mouse events, so
// manual calls to fx.hover will always run.
if(Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
return;
}
var dbb = evt.target.getBoundingClientRect();
xpx = evt.clientX - dbb.left;
ypx = evt.clientY - dbb.top;
// in case hover was called from mouseout into hovertext,
// it's possible you're not actually over the plot anymore
if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) {
return dragElement.unhoverRaw(gd, evt);
}
}
else {
if('xpx' in evt) xpx = evt.xpx;
else xpx = xaArray[0]._length / 2;
if('ypx' in evt) ypx = evt.ypx;
else ypx = yaArray[0]._length / 2;
}
if('xval' in evt) xvalArray = flat(subplots, evt.xval);
else xvalArray = p2c(xaArray, xpx);
if('yval' in evt) yvalArray = flat(subplots, evt.yval);
else yvalArray = p2c(yaArray, ypx);
if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
Lib.warn('Fx.hover failed', evt, gd);
return dragElement.unhoverRaw(gd, evt);
}
}
// the pixel distance to beat as a matching point
// in 'x' or 'y' mode this resets for each trace
var distance = Infinity;
// find the closest point in each trace
// this is minimum dx and/or dy, depending on mode
// and the pixel position for the label (labelXpx, labelYpx)
for(curvenum = 0; curvenum < searchData.length; curvenum++) {
cd = searchData[curvenum];
// filter out invisible or broken data
if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue;
trace = cd[0].trace;
subploti = subplots.indexOf(getSubplot(trace));
// within one trace mode can sometimes be overridden
mode = hovermode;
// container for new point, also used to pass info into module.hoverPoints
pointData = {
// trace properties
cd: cd,
trace: trace,
xa: xaArray[subploti],
ya: yaArray[subploti],
name: (gd.data.length > 1 || trace.hoverinfo.indexOf('name') !== -1) ? trace.name : undefined,
// point properties - override all of these
index: false, // point index in trace - only used by plotly.js hoverdata consumers
distance: Math.min(distance, constants.MAXDIST), // pixel distance or pseudo-distance
color: Color.defaultLine, // trace color
x0: undefined,
x1: undefined,
y0: undefined,
y1: undefined,
xLabelVal: undefined,
yLabelVal: undefined,
zLabelVal: undefined,
text: undefined
};
closedataPreviousLength = hoverData.length;
// for a highlighting array, figure out what
// we're searching for with this element
if(mode === 'array') {
var selection = evt[curvenum];
if('pointNumber' in selection) {
pointData.index = selection.pointNumber;
mode = 'closest';
}
else {
mode = '';
if('xval' in selection) {
xval = selection.xval;
mode = 'x';
}
if('yval' in selection) {
yval = selection.yval;
mode = mode ? 'closest' : 'y';
}
}
}
else {
xval = xvalArray[subploti];
yval = yvalArray[subploti];
}
// Now find the points.
if(trace._module && trace._module.hoverPoints) {
var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode);
if(newPoints) {
var newPoint;
for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
newPoint = newPoints[newPointNum];
if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
hoverData.push(cleanPoint(newPoint, hovermode));
}
}
}
}
else {
Lib.log('Unrecognized trace type in hover:', trace);
}
// in closest mode, remove any existing (farther) points
// and don't look any farther than this latest point (or points, if boxes)
if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
hoverData.splice(0, closedataPreviousLength);
distance = hoverData[0].distance;
}
}
// nothing left: remove all labels and quit
if(hoverData.length === 0) return dragElement.unhoverRaw(gd, evt);
// if there's more than one horz bar trace,
// rotate the labels so they don't overlap
var rotateLabels = hovermode === 'y' && searchData.length > 1;
hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });
var bgColor = Color.combine(
fullLayout.plot_bgcolor || Color.background,
fullLayout.paper_bgcolor
);
var labelOpts = {
hovermode: hovermode,
rotateLabels: rotateLabels,
bgColor: bgColor,
container: fullLayout._hoverlayer,
outerContainer: fullLayout._paperdiv
};
var hoverLabels = createHoverText(hoverData, labelOpts);
hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya');
alignHoverText(hoverLabels, rotateLabels);
// lastly, emit custom hover/unhover events
var oldhoverdata = gd._hoverdata,
newhoverdata = [];
// pull out just the data that's useful to
// other people and send it to the event
for(itemnum = 0; itemnum < hoverData.length; itemnum++) {
var pt = hoverData[itemnum];
var out = {
data: pt.trace._input,
fullData: pt.trace,
curveNumber: pt.trace.index,
pointNumber: pt.index,
x: pt.xVal,
y: pt.yVal,
xaxis: pt.xa,
yaxis: pt.ya
};
if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal;
newhoverdata.push(out);
}
gd._hoverdata = newhoverdata;
if(!hoverChanged(gd, evt, oldhoverdata)) return;
/* Emit the custom hover handler. Bind this like:
* gd.on('hover.plotly', function(extras) {
* // do something with extras.data
* });
*/
if(oldhoverdata) {
gd.emit('plotly_unhover', { points: oldhoverdata });
}
gd.emit('plotly_hover', {
points: gd._hoverdata,
xaxes: xaArray,
yaxes: yaArray,
xvals: xvalArray,
yvals: yvalArray
});
}
// look for either .subplot (currently just ternary)
// or xaxis and yaxis attributes
function getSubplot(trace) {
return trace.subplot || (trace.xaxis + trace.yaxis);
}
fx.getDistanceFunction = function(mode, dx, dy, dxy) {
if(mode === 'closest') return dxy || quadrature(dx, dy);
return mode === 'x' ? dx : dy;
};
fx.getClosest = function(cd, distfn, pointData) {
// do we already have a point number? (array mode only)
if(pointData.index !== false) {
if(pointData.index >= 0 && pointData.index < cd.length) {
pointData.distance = 0;
}
else pointData.index = false;
}
else {
// apply the distance function to each data point
// this is the longest loop... if this bogs down, we may need
// to create pre-sorted data (by x or y), not sure how to
// do this for 'closest'
for(var i = 0; i < cd.length; i++) {
var newDistance = distfn(cd[i]);
if(newDistance <= pointData.distance) {
pointData.index = i;
pointData.distance = newDistance;
}
}
}
return pointData;
};
function cleanPoint(d, hovermode) {
d.posref = hovermode === 'y' ? (d.x0 + d.x1) / 2 : (d.y0 + d.y1) / 2;
// then constrain all the positions to be on the plot
d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
d.y1 = Lib.constrain(d.y1, 0, d.ya._length);
// and convert the x and y label values into objects
// formatted as text, with font info
var logOffScale;
if(d.xLabelVal !== undefined) {
logOffScale = (d.xa.type === 'log' && d.xLabelVal <= 0);
var xLabelObj = Axes.tickText(d.xa,
d.xa.c2l(logOffScale ? -d.xLabelVal : d.xLabelVal), 'hover');
if(logOffScale) {
if(d.xLabelVal === 0) d.xLabel = '0';
else d.xLabel = '-' + xLabelObj.text;
}
else d.xLabel = xLabelObj.text;
d.xVal = d.xa.c2d(d.xLabelVal);
}
if(d.yLabelVal !== undefined) {
logOffScale = (d.ya.type === 'log' && d.yLabelVal <= 0);
var yLabelObj = Axes.tickText(d.ya,
d.ya.c2l(logOffScale ? -d.yLabelVal : d.yLabelVal), 'hover');
if(logOffScale) {
if(d.yLabelVal === 0) d.yLabel = '0';
else d.yLabel = '-' + yLabelObj.text;
}
else d.yLabel = yLabelObj.text;
d.yVal = d.ya.c2d(d.yLabelVal);
}
if(d.zLabelVal !== undefined) d.zLabel = String(d.zLabelVal);
// for box means and error bars, add the range to the label
if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
if(d.xerrneg !== undefined) {
d.xLabel += ' +' + xeText + ' / -' +
Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
}
else d.xLabel += ' ± ' + xeText;
// small distance penalty for error bars, so that if there are
// traces with errors and some without, the error bar label will
// hoist up to the point
if(hovermode === 'x') d.distance += 1;
}
if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
if(d.yerrneg !== undefined) {
d.yLabel += ' +' + yeText + ' / -' +
Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
}
else d.yLabel += ' ± ' + yeText;
if(hovermode === 'y') d.distance += 1;
}
var infomode = d.trace.hoverinfo;
if(infomode !== 'all') {
infomode = infomode.split('+');
if(infomode.indexOf('x') === -1) d.xLabel = undefined;
if(infomode.indexOf('y') === -1) d.yLabel = undefined;
if(infomode.indexOf('z') === -1) d.zLabel = undefined;
if(infomode.indexOf('text') === -1) d.text = undefined;
if(infomode.indexOf('name') === -1) d.name = undefined;
}
return d;
}
fx.loneHover = function(hoverItem, opts) {
// draw a single hover item in a pre-existing svg container somewhere
// hoverItem should have keys:
// - x and y (or x0, x1, y0, and y1):
// the pixel position to mark, relative to opts.container
// - xLabel, yLabel, zLabel, text, and name:
// info to go in the label
// - color:
// the background color for the label. text & outline color will
// be chosen black or white to contrast with this
// opts should have keys:
// - bgColor:
// the background color this is against, used if the trace is
// non-opaque, and for the name, which goes outside the box
// - container:
// a dom <svg> element - must be big enough to contain the whole
// hover label
var pointData = {
color: hoverItem.color || Color.defaultLine,
x0: hoverItem.x0 || hoverItem.x || 0,
x1: hoverItem.x1 || hoverItem.x || 0,
y0: hoverItem.y0 || hoverItem.y || 0,
y1: hoverItem.y1 || hoverItem.y || 0,
xLabel: hoverItem.xLabel,
yLabel: hoverItem.yLabel,
zLabel: hoverItem.zLabel,
text: hoverItem.text,
name: hoverItem.name,
idealAlign: hoverItem.idealAlign,
// filler to make createHoverText happy
trace: {
index: 0,
hoverinfo: ''
},
xa: {_offset: 0},
ya: {_offset: 0},
index: 0
};
var container3 = d3.select(opts.container),
outerContainer3 = opts.outerContainer ?
d3.select(opts.outerContainer) : container3;
var fullOpts = {
hovermode: 'closest',
rotateLabels: false,
bgColor: opts.bgColor || Color.background,
container: container3,
outerContainer: outerContainer3
};
var hoverLabel = createHoverText([pointData], fullOpts);
alignHoverText(hoverLabel, fullOpts.rotateLabels);
return hoverLabel.node();
};
fx.loneUnhover = function(containerOrSelection) {
var selection = containerOrSelection instanceof d3.selection ?
containerOrSelection :
d3.select(containerOrSelection);
selection.selectAll('g.hovertext').remove();
};
function createHoverText(hoverData, opts) {
var hovermode = opts.hovermode,
rotateLabels = opts.rotateLabels,
bgColor = opts.bgColor,
container = opts.container,
outerContainer = opts.outerContainer,
c0 = hoverData[0],
xa = c0.xa,
ya = c0.ya,
commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel',
t0 = c0[commonAttr],
t00 = (String(t0) || '').split(' ')[0],
outerContainerBB = outerContainer.node().getBoundingClientRect(),
outerTop = outerContainerBB.top,
outerWidth = outerContainerBB.width,
outerHeight = outerContainerBB.height;
// show the common label, if any, on the axis
// never show a common label in array mode,
// even if sometimes there could be one
var showCommonLabel = c0.distance <= constants.MAXDIST &&
(hovermode === 'x' || hovermode === 'y');
// all hover traces hoverinfo must contain the hovermode
// to have common labels
var i, traceHoverinfo;
for(i = 0; i < hoverData.length; i++) {
traceHoverinfo = hoverData[i].trace.hoverinfo;
var parts = traceHoverinfo.split('+');
if(parts.indexOf('all') === -1 &&
parts.indexOf(hovermode) === -1) {
showCommonLabel = false;
break;
}
}
var commonLabel = container.selectAll('g.axistext')
.data(showCommonLabel ? [0] : []);
commonLabel.enter().append('g')
.classed('axistext', true);
commonLabel.exit().remove();
commonLabel.each(function() {
var label = d3.select(this),
lpath = label.selectAll('path').data([0]),
ltext = label.selectAll('text').data([0]);
lpath.enter().append('path')
.style({fill: Color.defaultLine, 'stroke-width': '1px', stroke: Color.background});
ltext.enter().append('text')
.call(Drawing.font, HOVERFONT, HOVERFONTSIZE, Color.background)
// prohibit tex interpretation until we can handle
// tex and regular text together
.attr('data-notex', 1);
ltext.text(t0)
.call(svgTextUtils.convertToTspans)
.call(Drawing.setPosition, 0, 0)
.selectAll('tspan.line')
.call(Drawing.setPosition, 0, 0);
label.attr('transform', '');
var tbb = ltext.node().getBoundingClientRect();
if(hovermode === 'x') {
ltext.attr('text-anchor', 'middle')
.call(Drawing.setPosition, 0, (xa.side === 'top' ?
(outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) :
(outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD)))
.selectAll('tspan.line')
.attr({
x: ltext.attr('x'),
y: ltext.attr('y')
});
var topsign = xa.side === 'top' ? '-' : '';
lpath.attr('d', 'M0,0' +
'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE +
'H' + (HOVERTEXTPAD + tbb.width / 2) +
'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
'H-' + (HOVERTEXTPAD + tbb.width / 2) +
'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z');
label.attr('transform', 'translate(' +
(xa._offset + (c0.x0 + c0.x1) / 2) + ',' +
(ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')');
}
else {
ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end')
.call(Drawing.setPosition,
(ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE),
outerTop - tbb.top - tbb.height / 2)
.selectAll('tspan.line')
.attr({
x: ltext.attr('x'),
y: ltext.attr('y')
});
var leftsign = ya.side === 'right' ? '' : '-';
lpath.attr('d', 'M0,0' +
'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE +
'V' + (HOVERTEXTPAD + tbb.height / 2) +
'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) +
'V-' + (HOVERTEXTPAD + tbb.height / 2) +
'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');
label.attr('transform', 'translate(' +
(xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' +
(ya._offset + (c0.y0 + c0.y1) / 2) + ')');
}
// remove the "close but not quite" points
// because of error bars, only take up to a space
hoverData = hoverData.filter(function(d) {
return (d.zLabelVal !== undefined) ||
(d[commonAttr] || '').split(' ')[0] === t00;
});
});
// show all the individual labels
// first create the objects
var hoverLabels = container.selectAll('g.hovertext')
.data(hoverData, function(d) {
return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(',');
});
hoverLabels.enter().append('g')
.classed('hovertext', true)
.each(function() {
var g = d3.select(this);
// trace name label (rect and text.name)
g.append('rect')
.call(Color.fill, Color.addOpacity(bgColor, 0.8));
g.append('text').classed('name', true)
.call(Drawing.font, HOVERFONT, HOVERFONTSIZE);
// trace data label (path and text.nums)
g.append('path')
.style('stroke-width', '1px');
g.append('text').classed('nums', true)
.call(Drawing.font, HOVERFONT, HOVERFONTSIZE);
});
hoverLabels.exit().remove();
// then put the text in, position the pointer to the data,
// and figure out sizes
hoverLabels.each(function(d) {
var g = d3.select(this).attr('transform', ''),
name = '',
text = '',
// combine possible non-opaque trace color with bgColor
baseColor = Color.opacity(d.color) ?
d.color : Color.defaultLine,
traceColor = Color.combine(baseColor, bgColor),
// find a contrasting color for border and text
contrastColor = tinycolor(traceColor).getBrightness() > 128 ?
'#000' : Color.background;
if(d.name && d.zLabelVal === undefined) {
// strip out any html elements from d.name (if it exists at all)
// Note that this isn't an XSS vector, only because it never gets
// attached to the DOM
var tmp = document.createElement('p');
tmp.innerHTML = d.name;
name = tmp.textContent || '';
if(name.length > 15) name = name.substr(0, 12) + '...';
}
// used by other modules (initially just ternary) that
// manage their own hoverinfo independent of cleanPoint
// the rest of this will still apply, so such modules
// can still put things in (x|y|z)Label, text, and name
// and hoverinfo will still determine their visibility
if(d.extraText !== undefined) text += d.extraText;
if(d.zLabel !== undefined) {
if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '<br>';
if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '<br>';
text += (text ? 'z: ' : '') + d.zLabel;
}
else if(showCommonLabel && d[hovermode + 'Label'] === t0) {
text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || '';
}
else if(d.xLabel === undefined) {
if(d.yLabel !== undefined) text = d.yLabel;
}
else if(d.yLabel === undefined) text = d.xLabel;
else text = '(' + d.xLabel + ', ' + d.yLabel + ')';
if(d.text && !Array.isArray(d.text)) text += (text ? '<br>' : '') + d.text;
// if 'text' is empty at this point,
// put 'name' in main label and don't show secondary label
if(text === '') {
// if 'name' is also empty, remove entire label
if(name === '') g.remove();
text = name;
}
// main label
var tx = g.select('text.nums')
.style('fill', contrastColor)
.call(Drawing.setPosition, 0, 0)
.text(text)