-
Notifications
You must be signed in to change notification settings - Fork 2
/
simpledatavis.js
606 lines (536 loc) · 19.7 KB
/
simpledatavis.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
/* global btoa */
/**
* SimpleDataVis
*
* - JavaScript module for simple data visualizations
*
*/
;(function (win) {
var d3
var jsdom
if (typeof module !== 'undefined' && module.exports) {
global.XMLHttpRequest = require('xhr2') // d3.json won't work otherwise
d3 = require('d3')
jsdom = require('jsdom').jsdom
} else {
d3 = win.d3
}
function isArray (o) {
return Object.prototype.toString.call(o) === '[object Array]'
}
var SimpleDataVis = function (dataSource) {
function shallowCopy (orig) {
var copy = {}
for (var key in orig) {
copy[key] = orig[key]
}
return copy
}
function getErrorMsg (e) {
var msg
if (typeof e === 'string') {
msg = e
} else if (e.message) {
msg = e.message
} else if (e.response) {
msg = e.response
} else if ('status' in e) {
msg = (e.status ? e.status + ': ' : '') + (e.statusText || 'connection failed')
} else {
msg = JSON.stringify(e)
}
return msg
}
var getData = function (datasource, viewname, options, callbacks) {
if (isArray(datasource)) {
callbacks.done(datasource)
} else if (typeof datasource === 'function') {
var data = datasource()
callbacks.done(data)
} else if (typeof datasource === 'string') {
var url = datasource || win.location.origin
if (url.lastIndexOf('/') !== url.length - 1 && url.indexOf('?') === -1) {
url += '/'
}
var opts = options || {}
var params = opts.param || {}
if (opts.hasOwnProperty('group')) {
delete params['group_level']
if (opts.group.toString().toLowerCase() === 'true') {
params.group = true
} else if (opts.group.toString().toLowerCase() === 'false') {
params.group = false
} else if (!isNaN(opts.group)) {
params['group_level'] = opts.group
delete params.group
} else {
params.group = opts.group
}
}
if (opts.hasOwnProperty('startkey')) {
if (isArray(opts.startkey)) {
var s = opts.startkey.map(function (item) {
if (typeof item === 'string') return '"' + item + '"'
else if (typeof item === 'object') return '{}'
else return item
})
params.startkey = encodeURIComponent('[' + s.join() + ']')
} else {
params.startkey = opts.startkey
}
}
if (opts.hasOwnProperty('endkey')) {
if (isArray(opts.endkey)) {
var e = opts.endkey.map(function (item) {
if (typeof item === 'string') return '"' + item + '"'
else if (typeof item === 'object') return '{}'
else return item
})
params.endkey = encodeURIComponent('[' + e.join() + ']')
} else {
params.endkey = opts.endkey
}
}
var u = url + (viewname || '')
u += u.indexOf('?') === -1 ? '?' : '&'
for (var p in params) {
if (params[p]) {
u += (p + '=' + params[p] + '&')
}
}
while (u.lastIndexOf('?') === u.length - 1 || u.lastIndexOf('&') === u.length - 1 || u.lastIndexOf('/') === u.length - 1) {
u = u.substring(0, u.length - 1)
}
if (callbacks && typeof callbacks.onStart === 'function') {
callbacks.onStart(u)
}
var d3req = (d3.request || d3.xhr)(u)
var matches = url.match(/^https?:\/\/([^/]+):([^/]+)@/)
if (matches && matches.length > 2) {
d3req = d3req.header('Authorization', `Basic ${btoa(matches[1] + ':' + matches[2])}`)
}
d3req
.mimeType('application/json')
.response(function (xhr) { return JSON.parse(xhr.responseText) })
.get(function (error, json) {
if (error) {
console.error(error)
if (callbacks && typeof callbacks.onFail === 'function') {
callbacks.onFail(getErrorMsg(error))
}
} else if (callbacks && typeof callbacks.done === 'function') {
callbacks.done(json)
}
})
} else {
console.warn('SimpleDataVis - unexpected datasource provided:', datasource)
// perhaps it will be provided/corrected from the on-data callback
callbacks.done(datasource)
}
}
var visualizeData = function (type, options, callbacks) {
var clear = function (selection, exclude, callback) {
var n = 0
var s = selection.select('.simpledatavis')
var e = s.selectAll('*')
var start = function () { n++ }
var end = function () {
this.remove()
if (--n === 0 && callback) {
s.remove()
callback()
}
}
if (!s.empty() && (!exclude || !s.classed(exclude)) && (!e.empty())) {
var t = e.data([]).exit().transition()
.attr('opacity', 0)
.attr('width', 0)
if (d3.version.split('.')[0] === '3') {
t.each('start', start)
.each('end', end)
} else {
t.on('start', start)
.on('end', end)
}
} else if (callback) {
callback()
}
}
var message = function (selection, message) {
clear(d3.select(selection), 'message', function () {
var box = d3.select(selection).node().getBoundingClientRect()
var s = d3.select(selection).selectAll('svg').data([message])
s.enter().append('svg')
s.attr('width', box.width)
.attr('height', 200)
.attr('class', 'simpledatavis message')
var msg = s.selectAll('text.message').data([message])
msg.enter().append('text')
.attr('class', 'message')
.attr('opacity', 0)
.attr('x', 50)
.attr('y', 40)
msg.transition()
.attr('opacity', 1)
.text(message)
msg.exit().transition().attr('opacity', 0).remove()
})
}
var getVisualization = function (visdata) {
var vis = []
if (typeof type === 'string') {
vis = SimpleDataVis._visregistry.filter(function (v, index) {
return v.type === type
})
}
if (vis.length === 0) {
console.warn((type ? 'invalid vis type specified:' : 'no vis type specified:'), type)
vis = SimpleDataVis._visregistry.filter(function (v, index) {
if (typeof v.canRender === 'function') {
return v.canRender(visdata)
}
})
}
if (vis.length === 0) {
// default to table, if no valid visualizations found
console.warn('no valid vis found, using table-vis:', SimpleDataVis._visregistry.map(function (v, i) { return v.type }).join(','))
var tablevis = null
for (var v in SimpleDataVis._visregistry) {
if (SimpleDataVis._visregistry[v].type === 'table-vis') {
tablevis = SimpleDataVis._visregistry[v]
break
}
}
return tablevis
} else if (vis.length === 1) {
return vis[0]
} else {
// if more than one applicable visualization, get a random visualization
return vis[Math.floor((Math.random() * vis.length))]
}
}
var renderer = function (selection) {
selection.each(function (visdata) {
var that = this
var data = visdata ? (visdata.data || visdata) : []
if (data.length === 0) {
message(this, 'No results available')
if (typeof callbacks.onEnd === 'function') {
callbacks.onEnd(data)
}
} else {
var vis = getVisualization(visdata)
clear(d3.select(that), vis.type, function () {
vis.render(d3.select(that), visdata, options, callbacks)
// vis.render.call(that, visdata, options, callbacks)
var it = d3.select(that).select('*')
.classed('simpledatavis', true)
.classed(vis.type, true)
if (typeof callbacks.onEnd === 'function') {
callbacks.onEnd(data, it)
}
})
}
})
}
return renderer
}
var simpledatavis = function (datasource) {
var options = {}
var callbacks = {}
var scope = {}
var datavis = function (selection) {
var visOptions = shallowCopy(options)
var visCallback = shallowCopy(callbacks)
var visScope = shallowCopy(scope)
var onStart = function () {
if (typeof visCallback.start === 'function') {
visCallback.start.apply(selection, arguments)
} else if (typeof visCallback.start === 'string') {
if (visScope[visCallback.start]) {
visScope[visCallback.start].apply(selection, arguments)
} else if (win[visCallback.start]) {
win[visCallback.start].apply(selection, arguments)
}
}
}
var onFail = function () {
if (typeof visCallback.fail === 'function') {
visCallback.fail.apply(selection, arguments)
} else if (typeof visCallback.fail === 'string') {
if (visScope[visCallback.fail]) {
visScope[visCallback.fail].apply(selection, arguments)
} else if (win[visCallback.fail]) {
win[visCallback.fail].apply(selection, arguments)
}
}
}
var onData = function (data) {
var updated
if (typeof visCallback.data === 'function') {
updated = visCallback.data.apply(selection, arguments)
} else if (typeof visCallback.data === 'string') {
if (visScope[visCallback.data]) {
updated = visScope[visCallback.data].apply(selection, arguments)
} else if (win[visCallback.data]) {
updated = win[visCallback.data].apply(selection, arguments)
}
}
updated = (typeof updated === 'undefined') ? data : updated
return updated
}
var onEnd = function () {
if (typeof visCallback.end === 'function') {
visCallback.end.apply(selection, arguments)
} else if (typeof visCallback.end === 'string') {
if (visScope[visCallback.end]) {
visScope[visCallback.end].apply(selection, arguments)
} else if (win[visCallback.end]) {
win[visCallback.end].apply(selection, arguments)
}
}
}
var onClick = function () {
if (typeof visCallback.click === 'function') {
visCallback.click.apply(selection, arguments)
} else if (typeof visCallback.click === 'string') {
if (visScope[visCallback.click]) {
visScope[visCallback.click].apply(selection, arguments)
} else if (win[visCallback.click]) {
win[visCallback.click].apply(selection, arguments)
}
}
}
var done = function (data) {
var d = onData(data)
if (selection) {
d = (d && d.rows) ? d.rows : (d || [])
// in case options were changed during onData
var visOpts = shallowCopy(options)
if (typeof visOpts.tooltip === 'string') {
if (visScope[visOpts.tooltip]) {
visOpts.tooltip = visScope[visOpts.tooltip]
} else if (win[visOpts.tooltip]) {
visOpts.tooltip = win[visOpts.tooltip]
}
}
if (visCallback.click) {
visOpts.click = onClick
}
var renderer = visualizeData(visOpts.type, visOpts, { onFail: onFail, onEnd: onEnd })
selection
.style('color', '#264a60')
.style('fill', '#264a60')
.style('font-family', 'HelvNeue,Helvetica,sans-serif')
.style('font-size', '0.8rem')
.style('font-weight', '300')
.datum(d)
.call(renderer)
} else {
onEnd()
}
}
var cb = { onStart: onStart, onFail: onFail, done: done }
getData(datasource, visOptions.view, visOptions, cb)
}
datavis.attr = function (option, keyOrValue, value) {
if (typeof keyOrValue === 'undefined') {
return options[option]
} else if (keyOrValue == null) {
if (options.hasOwnProperty(option)) {
delete options[option]
}
} else if (option === 'param') {
if (keyOrValue == null) {
options['param'] = {}
} else if (typeof value === 'undefined') {
return options['param'][keyOrValue]
} else {
var param = (options['param'] || {})
if (keyOrValue === 'group_level' && options.hasOwnProperty('group')) {
delete options.group
}
param[keyOrValue] = value
options['param'] = param
}
} else {
if (option === 'group' && options.param && options.hasOwnProperty('group_level')) {
delete options.param['group_level']
}
options[option] = keyOrValue
}
return datavis
}
// callbacks include 'start', 'data', 'end', 'fail', click
datavis.on = function (callback, value) {
if (typeof value === 'undefined') {
return callbacks[callback]
} else if (value == null) {
if (callbacks.hasOwnProperty(callback)) {
delete callbacks[callback]
}
} else {
callbacks[callback] = value
}
return datavis
}
datavis.render = function (theselector, context) {
var selector = theselector
if (typeof module !== 'undefined' && module.exports) {
selector = d3.select(jsdom().documentElement).select('body')
}
if (context === null) {
scope = {}
} else if (typeof context === 'string') {
scope = win[context]
} else if (typeof context !== 'undefined') {
scope = context
}
if (typeof selector === 'string') {
d3.select(selector).call(datavis)
} else if (!selector) {
datavis()
} else if (typeof selector.call === 'function') {
selector.call(datavis)
} else {
var msg = 'datavis.render invalid selector: ' + selector
console.error(msg)
if (typeof callbacks.fail === 'function') {
callbacks.fail(msg)
} else if (typeof callbacks.fail === 'string') {
if (scope[callbacks.fail]) {
scope[callbacks.fail](msg)
} else if (win[callbacks.fail]) {
win[callbacks.fail](msg)
}
}
}
return datavis
}
return datavis
}
return simpledatavis(dataSource)
}
SimpleDataVis._visregistry = []
SimpleDataVis.register = function (typeStrOrNewVisObj, renderFunc) {
if (typeof typeStrOrNewVisObj === 'object' && typeof typeStrOrNewVisObj.type === 'string' && typeof typeStrOrNewVisObj.render === 'function') {
SimpleDataVis._visregistry.push(typeStrOrNewVisObj)
} else if (typeof typeStrOrNewVisObj === 'string' && typeof renderFunc === 'function') {
SimpleDataVis._visregistry.push({
type: typeStrOrNewVisObj,
render: renderFunc
})
}
}
SimpleDataVis.init = function (selection, context) {
var s = selection || d3.selectAll('[data-vis]')
s.each(function () {
var v = d3.select(this).attr('data-vis')
var dataurl = v // v.indexOf('http') == 0 ? v : (url + (v.indexOf('/') == 0 ? v.substring(1) : v))
if (dataurl) {
var vis = new SimpleDataVis(dataurl)
var attributes = this.attributes
var onPre = 'data-vis-on'
var paramPre = 'data-vis-param'
var attrPre = 'data-vis-'
for (var i = 0; i < attributes.length; i++) {
var attr = attributes[i]
if (attr.name.indexOf(onPre) === 0) {
vis.on(attr.name.substring(onPre.length), attr.value)
} else if (attr.name.indexOf(paramPre) === 0) {
var param = attr.value.split('=')
if (param.length === 2) {
vis.attr('param', param[0], param[1])
} else {
vis.attr('param', null)
}
} else if (attr.name.indexOf(attrPre) === 0) {
var attrName = attr.name.substring(attrPre.length)
vis.attr(attrName, attr.value)
}
}
vis.render(d3.select(this), context)
}
})
tooltipInit()
}
var tooltipInit = function () {
var format = d3.format(',')
var tooltipselection = null
var tip = function () {
tooltipselection =
d3.select('body')
.selectAll('.simpledatavis-tooltip')
.data(['simpledatavis-tooltip'])
if (d3.version.split('.')[0] === '3') {
tooltipselection.enter().append('div')
.attr('class', 'simpledatavis-tooltip')
} else {
tooltipselection = tooltipselection.enter().append('div')
.attr('class', 'simpledatavis-tooltip')
.merge(tooltipselection)
}
tooltipselection
.style('background-color', 'rgba(21, 41, 53, 0.9)')
.style('color', '#ffffff')
.style('font-family', 'HelvNeue,Helvetica,sans-serif')
.style('font-size', '0.75rem')
.style('font-weight', '300')
.style('max-width', '300px')
.style('padding', '8px')
.style('position', 'absolute')
.style('visibility', 'hidden')
.style('z-index', '100')
.text('simpledatavis-tooltip')
}
tip.mouseover = function (d, i, options, text) {
tooltipselection
.text(tip.text(d, i, options, text))
.style('visibility', 'visible')
}
tip.mousemove = function (d, i) {
tooltipselection
.style('top', (d3.event.pageY - 10) + 'px')
.style('left', (d3.event.pageX + 10) + 'px')
}
tip.mouseout = function (d, i) {
tooltipselection.style('visibility', 'hidden')
}
tip.text = function (d, i, options, text) {
return function () {
if (typeof options.tooltip === 'function') {
return options.tooltip(d)
} else if (typeof options.tooltip === 'string') {
return options.tooltip
} else if (typeof text === 'function') {
return text(d, i)
} else if (typeof text === 'string') {
return text
} else {
var msg = (d.data && d.data.key ? d.data.key : d.key) + ': ' + (typeof d.value === 'number' ? format(d.value) : d.value)
if (d.date) msg += ' , date: ' + d.date
if (d.geo) msg += ' , geo: ' + (d.geo.length && isArray(d.geo[0]) ? d.geo.length : d.geo)
return msg
}
}
}
tip()
SimpleDataVis.tooltip = tip
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = SimpleDataVis
require('./vis/simpledatavis-barchart')(SimpleDataVis)
require('./vis/simpledatavis-bubblechart')(SimpleDataVis)
require('./vis/simpledatavis-groupedbarchart')(SimpleDataVis)
require('./vis/simpledatavis-piechart')(SimpleDataVis)
require('./vis/simpledatavis-rangebarchart')(SimpleDataVis)
require('./vis/simpledatavis-stackedbarchart')(SimpleDataVis)
require('./vis/simpledatavis-timeline')(SimpleDataVis)
} else {
win.SimpleDataVis = SimpleDataVis
win.addEventListener('DOMContentLoaded', function () {
// find elements with data-vis-view attribute and initiate them
win.SimpleDataVis.init()
})
}
}(this))