forked from predixdesignsystem/px-vis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpx-vis-brush.html
557 lines (499 loc) · 19.3 KB
/
px-vis-brush.html
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
<link rel="import" href="../polymer/polymer.html"/>
<link rel="import" href="px-vis-behavior-common.html" />
<link rel="import" href="px-vis-behavior-d3.html" />
<link rel="import" href="../px-colors-design/colors.html" />
<!--
Element providing user interaction on the navigator.
This element draw the box over the navigator signifying the selected chart extents and provides the user interactions to resize and move the extent box.
This element sets the selectedDomain property based on the extents box. The selectedDomain variable can then be consumed by the scale component to change the main chart extents.
##### Usage
<px-vis-brush
svg="[[varFromSVGComponent]]"
axis="[[varXFromScaleComponent]]"
width="[[width]]"
height="[[height]]"
margin="[[margin]]"
chart-domain=[[chartDomainX]]
current-domain="[[varXDomainFromScaleComponent]]"
gradient-overlay="[[gradientOverlay]]"
selected-domain="{{selectedDomain}}">
</px-vis-brush>
@element px-vis-brush
@blurb Element providing user interaction on the navigator.
@homepage index.html
@demo demo.html
-->
<link rel="import" href="css/px-vis-styles.html">
<dom-module id="px-vis-brush">
<template>
<style include="px-vis-styles"></style>
</template>
</dom-module>
<script>
Polymer({
is: 'px-vis-brush',
behaviors: [
PxVisBehavior.sizing,
PxVisBehaviorD3.svg,
PxVisBehaviorD3.axis,
PxVisBehaviorD3.selectedDomain,
PxVisBehavior.commonMethods,
PxVisBehaviorD3.domainUpdate,
PxColorsBehavior.baseColors
],
/**
* Properties block, expose attribute values to the DOM via 'reflect'
*
* @property properties
* @type Object
*/
properties: {
/**
* Holder for the d3.svg.brush() object
*
* See: https://github.com/mbostock/d3/wiki/SVG-Controls
*
*/
_brush:{
type: Object,
value: function() { return{}; }
},
/**
* Holder for a SVG group of elements pertaining to the brush
*
*/
_brushGroup:{
type: Object,
value: function() {return{};}
},
/**
* Holder for a SVG group of elements pertaining to the handles
*
*/
_handleGroup:{
type: Object,
value: function() {return{};}
},
/**
* Holder for a calculated center of the extent box
*
*/
_center:{
type:Object,
value: function() {return{};}
},
/**
* A boolean to tell if the extents box is currently moving
*
*/
_centering:{
type:Boolean,
value:false
},
/**
* A boolean to tell if a handle is currently moving
*
*/
_brushing:{
type:Boolean,
value:false
},
/**
* The parent chart's extents
*
*/
chartDomain: {
type:Object,
notify:true
},
/**
* Boolean specifying if the rectangle overlay should have a gradient applied
*
*/
gradientOverlay: {
type: Boolean,
value: false
},
/**
* Allows to prevent changes to selectedDomain
*/
_preventDomainChange: {
type: Boolean,
value: false
},
_animationFrameDone: {
type: Boolean,
value: false
}
},
observers: [
'drawElement(domainChanged, svg,axis,height, selectedDomain, currentDomain, _animationFrameDone)',
'_zoomBrush(chartDomain.*)'
],
detached: function() {
this.unlisten(window,'mouseup','_brushMouseUp');
},
ready: function() {
window.requestAnimationFrame(function() {
this.set('_animationFrameDone', true);
}.bind(this));
},
/**
* Defines the svg for the brush, draws brush elements, and sets up listeners.
*
* Fired though an observer looking at currentDomain.
*
* Can be called manually after svg and currentDomain are set.
*
* @method drawElement
*/
drawElement: function() {
if(this._animationFrameDone && this.currentDomain && this.currentDomain.length === 2 && !isNaN(this.currentDomain[0].getTime()) && !isNaN(this.currentDomain[1].getTime())) {
var heightOffset = 5,
h = Math.max(this.height - this.margin.bottom - heightOffset,0),
domain = [
[this.axis(this.currentDomain[0]),0],
[this.axis(this.currentDomain[1]),h]
];
// check that our sizing is ok and wont freak d3 out.
// x2 and y2 must be greater than x1 & y1
domain[1][0] = (domain[1][0] > domain[0][0]) ? domain[1][0] : domain[0][0];
domain[1][1] = (domain[1][1] > domain[0][1]) ? domain[1][1] : domain[0][1];
if(this._isObjEmpty(this._brush)) {
// first, define the brush using the axis
this._brush = Px.d3.brushX()
.extent(domain)
.handleSize(6)
.on("start", this._brushstart.bind(this))
.on("brush", this._brushmove.bind(this))
.on("end", this._brushend.bind(this));
// now that we have our new g, proceed with drawing brush
this._brushGroup = this.svg.append("g")
.attr("class", "brush")
.call(this._brush)
.call(this._brush.move, this.axis.range());
/* Style the brush overlay box
There are actually two boxes, .selection and .overlay:
overlay captures the mouse events; selection is what is visible
*/
var overlay = this._brushGroup.select("rect.selection")
.attr("y", 0)
.attr('stroke', this._checkThemeVariable("--px-vis-nav-brush-outline-color", this.colors.gray5))
.attr('stroke-width',2)
.attr('shape-rendering','crispEdges');
if(this.gradientOverlay){
var gradient = this.svg.append("defs")
.append("linearGradient")
.attr("id", "overlayGradient");
gradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", this._checkThemeVariable("--px-vis-nav-brush-gradient-fill-color", this.colors.grey5))
.attr("stop-opacity", this._checkThemeVariable("--px-vis-nav-brush-gradient-opacity-1", 0.2));
gradient.append("stop")
.attr("offset", "100%")
.attr("stop-color", this._checkThemeVariable("--px-vis-nav-brush-gradient-fill-color", this.colors.grey5))
.attr("stop-opacity", this._checkThemeVariable("--px-vis-nav-brush-gradient-opacity-2", 0.8));
overlay.attr('fill','url(#overlayGradient)')
.attr('fill-opacity','1.0');
} else {
overlay.attr('fill',this._checkThemeVariable("--px-vis-nav-brush-fill-color", this.colors.black))
.attr('fill-opacity', this._checkThemeVariable("--px-vis-nav-brush-opacity", 0.10))
}
this._drawHandles(heightOffset);
// // Setup listeners for click on the navigator so the brush will jump instead of redraw
this._brushGroup.select("rect.overlay")
.on("mousedown.brush", this._brushcenter.bind(this))
.on("touchstart.brush", this._brushcenter.bind(this));
//if we want fancy color changes, etc, can use brushstart to prime those changes
// this._brushstart();
// this._brushmove();
// this._brush.extent(this.currentDomain);
//
// console.log(this._brushGroup.node().parentNode.childNodes);
// var nodes = this._brushGroup.node().parentNode.childNodes;
// console.log(nodes[nodes.length -1]);
// if(nodes[nodes.length -1] !== this._brushGroup.node()){
// console.log("doesnt match");
// }
} else {
//make sure brush has the right size
this._brush.extent(domain)
.handleSize(6)
.on("start", this._brushstart.bind(this))
.on("brush", this._brushmove.bind(this))
.on("end", this._brushend.bind(this));
if(this.selectedDomain && this.selectedDomain.x.length > 0) {
//redraw the brush in the right place, but make sure we don't fire a change of domain
this._preventDomainChange = true;
this._brushGroup
.call(this._brush)
.call(this._brush.move, [this.axis(this.selectedDomain.x[0]), this.axis(this.selectedDomain.x[1])]);
this._preventDomainChange = false;
}
}
}
},
/**
* Helper function to add class "selecting" to elems selected in the brush
*
* @method _brushstart
*/
_brushstart: function() {
this.set("_brushing", true);
//TODO do we want to issue a color change? if not, delete/ comment out
this.svg.classed("selecting", true);
},
/**
* Helper function to remove class "selecting" to elems not selected in the brush
*
* @method _brushend
*/
_brushend: function () {
this.set("_brushing", false);
// revert our handle style to normal
if(this._doesObjHaveValues(this._handleGroup)){
this._handleGroup.dispatch('brushmouseup');
}
// console.log(d3.event.selection);
//TODO do we want to issue a color change? if not, delete/ comment out
this.svg.classed("selecting", false);
},
/**
* Helper function fired whtn the brush is moved / extents changed
* sets the attr 'selectedDomain' with the new extents
* this attr should travel up the compent tree via observers and set the new domain in the chart
*
* @method _brushmove
*/
_brushmove: function() {
// var s = d3.event.selection;
// circle.classed("selected", function(d) { return s[0] <= d && d <= s[1]; });
this.debounce('brushed', function () {
if(Px.d3.brushSelection(this._brushGroup.node())) {
var brushExt = Px.d3.brushSelection(this._brushGroup.node());
//if our extents are the same, add or subtract one based on location and reset the brush
if(brushExt[0] === brushExt[1]) {
brushExt[0] = (brushExt[0] === 0) ? 0 : brushExt[1] - 1;
brushExt[1] = (brushExt[1] === 0) ? brushExt[0] + 1 : brushExt[1];
this._brushGroup
.call(this._brush.move,brushExt)
} else {
var newDomain = brushExt.map(this.axis.invert, this.axis),
//make sure this is an actual update
changed = this.selectedDomain.x.length < 2 ||
newDomain[0].toString() !== this.selectedDomain.x[0].toString() ||
newDomain[1].toString() !== this.selectedDomain.x[1].toString();
if(!this._preventDomainChange && changed) {
this.set('selectedDomain', {x:newDomain,y:[]});
this.fire('px-vis-selected-domain-updated', {
'data':{x:newDomain,y:[]}, 'method': 'set', 'dataVar': 'selectedDomain'
});
}
}
}
}, 10);
},
/**
* Helper function fired whtn the navigator is clicked on
*
* @method _brushcenter
*/
_brushcenter: function() {
var win = Px.d3.select(window), // window
target = Px.d3.event.target, //this._brushGroup
extent = Px.d3.brushSelection(this._brushGroup.node()), //array of brush currect size in pixelspace
size = extent[1] - extent[0], //width in pixels
range = this.axis.range(), //overall extents in pixelspace
x0 = range[0] + size / 2,
x1 = range[1] - size / 2;
this._recenter(true);
this._brushcentermove(target,x0,x1);
if (Px.d3.event.changedTouches) {
win.on("touchmove.brush", this._brushcentermove.bind(this,target,x0,x1))
.on("touchend.brush", this._brushcenterend.bind(this));
} else {
win.on("mousemove.brush", this._brushcentermove.bind(this,target,x0,x1))
.on("mouseup.brush", this._brushcenterend.bind(this));
}
}, //_brushcenter
/**
* Helper function to calculate the centerpoint where the brush should move to
*
* @method _brushcentermove
*/
_brushcentermove: function(target,x0,x1) {
Px.d3.event.stopPropagation();
// calc the center or pick an edge
this._center = Math.max(x0, Math.min(x1, Px.d3.mouse(target)[0]));
this._recenter(false);
},
/**
* Helper function to to call the currentDomain function and disable listner
*
* @method _brushcenterend
*/
_brushcenterend: function() {
this._brushmove();
Px.d3.select(window).on(".brush", null);
},
/**
* Helper function to tween and calculate the brush move
*
* @method _recenter
*/
_recenter: function(smooth) {
var _this = this;
if (this._centering) {
return; // timer is active and already tweening
}
if (!smooth) {
return void _this.tween(1); // instantaneous jump
}
this._centering = true;
// sets up a timer to call tween
var timer = Px.d3.timer(function() {
_this.tween(0.2);
// stop the timer when we have centered
if(!_this._centering){
timer.stop();
}
});
},
/**
* Helper function to tween so that the brush slides rather than a jumps
*
* @method tween
* @private
*/
tween:function (alpha) {
var extent = Px.d3.brushSelection(this._brushGroup.node()), //recalc every time it moves
size = extent[1] - extent[0],
center1 = this._center * alpha + ( extent[0] + extent[1]) / 2 * (1 - alpha);
// move the brush
this._brushGroup
.call(this._brush.move,[center1 - size / 2, center1 + size / 2]);
// .call(this._brush.event);
// TODO check that it works with radically different extents, such as 0.0-1.0
// check if it has moved into position within a tolerance (based on overall size of the domain)
this._centering = Math.abs((center1) - (this._center)) > size * 0.01;
},
/**
* Helper function to draw the handle elements
*
* @method _drawHandles
*/
_drawHandles:function(heightOffset){
// Setup sizes for the handles on either end
var handleSize = {
'h':32,
'w':9,
's':1.5
};
// handleSize['y'] = this.height/2 - handleSize.h/2 - heightOffset;
//
// var lineY = [handleSize.y + heightOffset * 1.5 , handleSize.y + handleSize.h - heightOffset * 1.5];
//draw a group to hold the handles
// this._handleGroup = this._brushGroup.selectAll(".handle")
this._handleGroup = this._brushGroup.selectAll(".handle")
// provide listeners for hover and press events
.on('brushmouseup',this._handleGroupMouseUp.bind(this))
.on('mousedown.handle',this._handleGroupMouseDown.bind(this))
.on("mouseenter.handle", this._handleGroupMouseEnter.bind(this))
.on("mouseleave.handle", this._handleGroupMouseLeave.bind(this));
// draw the handle rect / base
this._handleGroup
// .attr("x", -handleSize.w/2)
// .attr("y", handleSize.y)
// .attr("height", handleSize.h)
.attr('stroke',this._checkThemeVariable("--px-vis-nav-brush-handle-lines-color", this.colors.gray5))
.attr('fill',this._checkThemeVariable("--px-vis-nav-brush-handle-fill-color", this.colors.white))
.attr('shape-rendering','crispEdges');
// draw the lines for the handles
// this._handleGroup.append("svg:line")
// .attr("x1", handleSize.s )
// .attr("x2", handleSize.s )
// .attr("y1", lineY[0])
// .attr("y2", lineY[1])
// .attr("class", "handleLine")
// .attr('fill','none')
// .attr('stroke',this.colors.gray5);
//
// this._handleGroup.append("svg:line")
// .attr("x1", -handleSize.s )
// .attr("x2", -handleSize.s )
// .attr("y1", lineY[0])
// .attr("y2", lineY[1])
// .attr("class", "handleLine")
// .attr('fill','none')
// .attr('stroke',this.colors.gray5);
},
/**
* Function to restyle handles on mousedown event
*
* @method _handleGroupMouseDown
*/
_handleGroupMouseDown:function(d,i){
var elem = Px.d3.select(this._handleGroup.nodes()[i]);
// disable changes on mouseleave because when a person drags, they can leave the elem bounds and we dont want to restyle yet.
elem.on("mouseleave.handle", null);
// set the pressed styles
elem.attr('stroke', this._checkThemeVariable("--px-vis-nav-brush-handle-lines-color-press", this.colors.gray7))
.attr('fill', this._checkThemeVariable("--px-vis-nav-brush-handle-fill-color-press", this.colors.gray6));
// elem.selectAll('line.handleLine')
// .attr('stroke', this.colors.gray7);
},
/**
* Function to restyle handles on mouseup event
*
* @method _handleGroupMouseUp
*/
_handleGroupMouseUp:function(d,i){
var elem = Px.d3.select(this._handleGroup.nodes()[i]);
// reapply the mouseleave function and again, bind our index
elem.on("mouseleave.handle", this._handleGroupMouseLeave.bind(this,d,i));
elem.attr('stroke',this._checkThemeVariable("--px-vis-nav-brush-handle-lines-color", this.colors.gray5))
.attr('fill',this._checkThemeVariable("--px-vis-nav-brush-handle-fill-color", this.colors.white));
// elem.selectAll('line.handleLine')
// .attr('stroke', this.colors.gray5);
},
/**
* Function to restyle handles on mouseleave event
*
* @method _handleGroupMouseLeave
*/
_handleGroupMouseLeave:function(d,i){
var elem = Px.d3.select(this._handleGroup.nodes()[i]);
elem.attr('stroke',this._checkThemeVariable("--px-vis-nav-brush-handle-lines-color", this.colors.gray5))
.attr('fill',this._checkThemeVariable("--px-vis-nav-brush-handle-fill-color", this.colors.white))
// elem.selectAll('line.handleLine')
// .attr('stroke', this.colors.gray5);
},
/**
* Function to restyle handles on mouseenter event
*
* @method _handleGroupMouseEnter
*/
_handleGroupMouseEnter:function(d,i){
var elem = Px.d3.select(this._handleGroup.nodes()[i]);
elem.attr('stroke',this._checkThemeVariable("--px-vis-nav-brush-handle-lines-color-hover", this.colors.gray6))
.attr('fill',this._checkThemeVariable("--px-vis-nav-brush-handle-fill-color-hover", this.colors.gray5));
// elem.selectAll('line.handleLine')
// .attr('stroke', this.colors.gray6);
},
/**
* Function to trigger a brush extent calculation when the main chart extents change.
*
* @method _zoomBrush
*/
_zoomBrush: function(chartDomain){
if(!this._brushing && !this._centering && this.chartDomain.length > 0 && this._doesObjHaveValues(this._brush) && this._doesObjHaveValues(this._brushGroup) && this._doesObjHaveValues(this.axis) && Px.d3.brushSelection(this._brushGroup.node())){
var extent = Px.d3.brushSelection(this._brushGroup.node()),
domain = [this.axis(this.chartDomain[0]),this.axis(this.chartDomain[1])];
if(!(extent[0] === domain[0] && extent[1] === domain[1])){
this._brushGroup
.call(this._brush.move,domain)
}
}
},
});
</script>