-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
416 lines (324 loc) · 11.5 KB
/
index.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
'use strict';
var _ = require('lodash');
var request = require('superagent');
var d3Color = require('d3-color');
var d3Scale = require('d3-scale');
var colorbrewer = require('colorbrewer')
var Color = require('color');
var closest = require('closest');
var r;
var utils = {
preloadImages: function(urls) {
_.each(urls, function(url) {
utils.preloadImage(url);
});
},
preloadImage: function(url) {
var img=new Image();
img.src=url;
},
randomColor: function() {
return '#'+Math.floor(Math.random()*16777215).toString(16);
},
linspace: function(a, b, n) {
var every = (b-a)/(n-1);
var ranged = _.range(a, b, every);
return ranged.length == n ? ranged : ranged.concat(b);
},
getThumbnail: function(image) {
return image + '_small';
},
cleanImageURL: function(url) {
if(url.indexOf('http') > -1) {
return url;
}
return (window.lightning && window.lightning.host) ? window.lightning.host + url : url;
},
mapRange: function(value, istart, istop, ostart, ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
},
getColors: function(n) {
var colors = ['#A38EF3', '#7ABFEA', '#5BC69F', '#E96B88', '#F0E86B', '#C2B08C', '#F9B070', '#F19A9A', '#AADA90', '#DBB1F2'];
var retColors = [];
for(var i = 0; i<n; i++) {
retColors.push(colors[ i % colors.length]);
}
return retColors;
},
getColorFromData: function(data) {
// retrieve an array of colors from 'label' or 'color' fields of object data
// returns an list of lists in the form [[r,g,b],[r,g,b]...]
var retColor, color;
if(data.hasOwnProperty('group')) {
// get bounds and number of group labels
var group = data.group;
var mn = Math.min.apply(null, group);
var mx = Math.max.apply(null, group);
var n = mx - mn + 1;
var colors = this.getColors(n);
// get an array of d3 colors
retColor = group.map(function(d) { return d3Color.rgb(colors[d - mn]); });
} else if (data.hasOwnProperty('color')) {
// get an array of d3 colors directly from r,g,b values
color = data.color;
retColor = color.map(function(d) {return d3Color.rgb(d[0], d[1], d[2]); });
} else if (data.hasOwnProperty('values')) {
var values = data.values;
// get distinct values
var distinct = _.uniq(data.values).length
if (distinct > 8) {
distinct = 8
}
// get colorbrewer colors from a linear scale
var colormap = data.colormap ? data.colormap : 'Purples';
if (colormap == 'Lightning') {
color = this.getColors(distinct)
} else {
color = colorbrewer[colormap][distinct];
}
// get min and max of value data
var vmin = Math.min.apply(null, values);
var vmax = Math.max.apply(null, values);
// set up scales
var domain = this.linspace(vmin, vmax, distinct);
var scale = d3Scale.linear().domain(domain).range(color);
retColor = values.map(function(d) { return d3Color.rgb(scale(d)); });
} else {
// otherwise return empty
retColor = [];
}
return retColor;
},
buildRGBA: function(base, opacity) {
var color = Color(base);
color.alpha(opacity);
return color.rgbString();
},
trackTransforms: function(ctx){
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
var xform = svg.createSVGMatrix();
ctx.getTransform = function(){ return xform; };
var savedTransforms = [];
var save = ctx.save;
ctx.save = function(){
savedTransforms.push(xform.translate(0,0));
return save.call(ctx);
};
var restore = ctx.restore;
ctx.restore = function(){
xform = savedTransforms.pop();
return restore.call(ctx);
};
var scale = ctx.scale;
ctx.scale = function(sx,sy){
var oldXForm = xform;
xform = xform.scaleNonUniform(sx,sy);
if(xform.d < 1) {
xform = oldXForm;
return;
}
return scale.call(ctx,sx,sy);
};
var rotate = ctx.rotate;
ctx.rotate = function(radians){
xform = xform.rotate(radians*180/Math.PI);
return rotate.call(ctx,radians);
};
var translate = ctx.translate;
ctx.translate = function(dx,dy){
xform = xform.translate(dx,dy);
return translate.call(ctx,dx,dy);
};
var transform = ctx.transform;
ctx.transform = function(a,b,c,d,e,f){
var m2 = svg.createSVGMatrix();
m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
xform = xform.multiply(m2);
return transform.call(ctx,a,b,c,d,e,f);
};
var setTransform = ctx.setTransform;
ctx.setTransform = function(a,b,c,d,e,f){
xform.a = a;
xform.b = b;
xform.c = c;
xform.d = d;
xform.e = e;
xform.f = f;
return setTransform.call(ctx,a,b,c,d,e,f);
};
var pt = svg.createSVGPoint();
ctx.transformedPoint = function(x,y) {
pt.x=x; pt.y=y;
return pt.matrixTransform(xform.inverse());
};
},
addCanvasZoomPanListeners: function(canvas, context, redraw) {
var lastX= canvas.width / 2;
var lastY = canvas.height / 2;
var dragStart, dragged;
canvas.addEventListener('mousedown',function(evt){
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
dragStart = context.transformedPoint(lastX,lastY);
dragged = false;
}, false);
canvas.addEventListener('mousemove',function(evt){
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
dragged = true;
if (dragStart){
var pt = context.transformedPoint(lastX,lastY);
context.translate(pt.x-dragStart.x,pt.y-dragStart.y);
redraw();
}
},false);
canvas.addEventListener('mouseup',function(evt){
dragStart = null;
if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
},false);
var scaleFactor = 1.025;
var zoom = function(clicks){
var pt = context.transformedPoint(lastX,lastY);
context.translate(pt.x, pt.y);
var factor = Math.pow(scaleFactor,clicks);
context.scale(factor,factor);
context.translate(-pt.x, -pt.y);
redraw();
};
var handleScroll = function(evt){
var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
if (delta) zoom(delta);
return evt.preventDefault() && false;
};
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
canvas.addEventListener('mousewheel',handleScroll,false);
},
isEditorOrPreview: function() {
var url = document.URL;
return /https?:\/\/[^\/]+\/visualization-types\/*/.test(url);
},
getId: function(viz) {
/*
* TODO - move this logic to the visualization base class
* so we aren't passing around viz objects everywhere
*/
var el = viz.el;
if(!el) {
console.log('heher');
el = $(viz.selector)[0];
}
return closest(el, '[data-model=visualization]', true).dataset.modelId;
},
getUrl: function(viz) {
/*
* TODO - move this logic to the visualization base class
* so we aren't passing around viz objects everywhere
*/
var vid = this.getId(viz);
var host = '/';
if(window.lightning && window.lightning.host) {
host = window.lightning.host;
}
return host + 'visualizations/' + vid;
},
fetchData: function(viz, keys, cb) {
if(!viz.$el) {
console.warn('Must set .$el property on your visualization');
}
if(this.isEditorOrPreview()) {
setTimeout(function() {
var data = $('#data-editor').next('.CodeMirror').find('.CodeMirror-code span')[0].innerHTML;
var fetchedData = JSON.parse(data);
_.each(keys, function(key) {
fetchedData = fetchedData[key];
});
cb(null, fetchedData);
}, 0);
} else {
var url = this.getUrl(viz);
if(r) {
r.abort();
}
r = request.get(url + '/data/' + keys.join('/') + '/', function(err, res) {
if(err) {
return cb(err);
}
cb(null, (res.body || {}).data);
});
}
},
getSettings: function(viz, cb) {
if(this.isEditorOrPreview()) {
setTimeout(function() {
cb(null, {});
}, 0);
return;
}
var url = this.getUrl(viz);
r = request.get(url + '/settings/', function(err, res) {
if(err) {
return cb(err);
}
cb(null, (res.body || {}).settings);
});
},
getUniqueId: function() {
var s4 = function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
},
updateSettings: function(viz, settings, cb) {
if(this.isEditorOrPreview()) {
setTimeout(function() {
cb(null, settings);
}, 0);
return;
}
var url = this.getUrl(viz);
console.log('settings');
console.log(settings);
r = request.post(url + '/settings/', settings, function(err, res) {
if(err) {
return cb(err)
}
cb && cb(null, (res.body || {}).settings);
});
},
getCommForViz: function(viz) {
var m = (window.lightning || {}).comm_map;
if(m) {
return m[this.getId(viz)];
}
},
sendCommMessage: function(viz, type, data) {
var comm = this.getCommForViz(viz);
if(comm) {
comm.send(JSON.stringify({
type: type,
data: data
}));
}
},
nearestPoint: function(points, target, xscale, yscale) {
// find point in points nearest to target
// using scales x and y
// point must have attrs x, y, and s
var i = 0, count = 0;
var found, dist, n, p;
while (count == 0 & i < points.length) {
p = points[i]
dist = Math.sqrt(Math.pow(xscale(p.x) - target[0], 2) + Math.pow(yscale(p.y) - target[1], 2))
if (dist <= p.s) {
found = p
count = 1
}
i++;
}
return found
}
};
module.exports = utils;