-
Notifications
You must be signed in to change notification settings - Fork 52
/
d3-jetpack.cjs
558 lines (464 loc) 路 17.6 KB
/
d3-jetpack.cjs
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
// https://github.com/gka/d3-jetpack#readme Version 2.1.1. Copyright 2021 Gregor Aisch.
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-selection'), require('d3-transition'), require('d3-array'), require('d3-axis'), require('d3-scale'), require('d3-collection'), require('d3-queue'), require('d3-request'), require('d3-timer')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-selection', 'd3-transition', 'd3-array', 'd3-axis', 'd3-scale', 'd3-collection', 'd3-queue', 'd3-request', 'd3-timer'], factory) :
(factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3));
}(this, (function (exports,d3Selection,d3Transition,d3Array,d3Axis,d3Scale,d3Collection,d3Queue,d3Request,d3Timer) { 'use strict';
var translateSelection = function(xy, dim) {
var node = this.node();
return !node ? this : node.getBBox ?
this.attr('transform', function(d,i) {
var p = typeof xy == 'function' ? xy.call(this, d,i) : xy;
if (dim === 0) p = [p, 0]; else if (dim === 1) p = [0, p];
return 'translate(' + p[0] +','+ p[1]+')';
}) :
this.style('transform', function(d,i) {
var p = typeof xy == 'function' ? xy.call(this, d,i) : xy;
if (dim === 0) p = [p, 0]; else if (dim === 1) p = [0, p];
return 'translate(' + p[0] +'px,'+ p[1]+'px)';
});
};
var parseAttributes = function(name) {
if (typeof name === "string") {
var attr = {},
parts = name.split(/([\.#])/g), p;
name = parts.shift();
while ((p = parts.shift())) {
if (p == '.') attr['class'] = attr['class'] ? attr['class'] + ' ' + parts.shift() : parts.shift();
else if (p == '#') attr.id = parts.shift();
}
return {tag: name, attr: attr};
}
return name;
};
var append = function(name) {
var create, n;
if (typeof name === "function"){
create = name;
} else {
n = parseAttributes(name);
create = d3Selection.creator(n.tag);
}
var sel = this.select(function(){
return this.appendChild(create.apply(this, arguments));
});
if (n) for (var key in n.attr) { sel.attr(key, n.attr[key]); }
return sel;
};
function constantNull() {
return null;
}
var insert = function(name, before) {
var n = parseAttributes(name),
create = d3Selection.creator(n.tag),
select$$1 = before == null ? constantNull : typeof before === "function" ? before : d3Selection.selector(before);
var s = this.select(function() {
return this.insertBefore(create.apply(this, arguments), select$$1.apply(this, arguments) || null);
});
//attrs not provided by default in v4
for (var key in n.attr) { s.attr(key, n.attr[key]); }
return s;
};
var parent = function() {
var parents = [];
return this.filter(function() {
if (parents.indexOf(this.parentNode) > -1) return false;
parents.push(this.parentNode);
return true;
}).select(function() {
return this.parentNode;
});
};
var selectAppend = function(name) {
var select$$1 = d3Selection.selector(name),
n = parseAttributes(name), s;
name = d3Selection.creator(n.tag);
s = this.select(function() {
return select$$1.apply(this, arguments) ||
this.appendChild(name.apply(this, arguments));
});
//attrs not provided by default in v4
for (var key in n.attr) { s.attr(key, n.attr[key]); }
return s;
};
var tspans = function(lines, lh) {
return this.selectAll('tspan')
.data(function(d, i) {
return (typeof(lines) === 'function' ? lines.call(this, d, i) : lines)
.map(function(l) {
return { line: l, parent: d };
});
})
.enter()
.append('tspan')
.text(function(d) { return d.line; })
.attr('x', 0)
.attr('dy', function(d, i) { return i ? (typeof(lh) === 'function' ? lh.call(this, d.parent, d.line, i) : lh) || 15 : 0; });
};
var appendMany = function(name, data){
if (typeof(data) == 'string'){
console.warn("DEPRECATED: jetpack's appendMany order of arguments has changed. It's appendMany('div', data) from now on");
var temp = data;
data = name;
name = temp;
}
return this.selectAll(null).data(data).enter().append(name);
};
const camelCaseAttrs = /^(allowReorder|attributeName|attributeType|autoReverse|baseFrequency|baseProfile|calcMode|clipPathUnits|contentScriptType|contentStyleType|diffuseConstant|edgeMode|externalResourcesRequired|filterRes|filterUnits|glyphRef|gradientTransform|gradientUnits|kernelMatrix|kernelUnitLength|keyPoints|keySplines|keyTimes|lengthAdjust|limitingConeAngle|markerHeight|markerUnits|markerWidth|maskContentUnits|maskUnits|numOctaves|pathLength|patternContentUnits|patternTransform|patternUnits|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|referrerPolicy|refX|refY|repeatCount|repeatDur|requiredExtensions|requiredFeatures|specularConstant|specularExponent|spreadMethod|startOffset|stdDeviation|stitchTiles|surfaceScale|systemLanguage|tableValues|targetX|targetY|textLength|viewBox|viewTarget|xChannelSelector|yChannelSelector|zoomAndPan)$/;
var at = function(name, value) {
if (typeof(name) == 'object'){
for (var key in name){
this.attr(camelCaseAttrs.test(key) ? key : key.replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase(), name[key]);
}
return this;
} else{
return arguments.length == 1 ? this.attr(name) : this.attr(name, value);
}
};
function f(){
var functions = arguments;
//convert all string arguments into field accessors
var i = 0, l = functions.length;
while (i < l) {
if (typeof(functions[i]) === 'string' || typeof(functions[i]) === 'number'){
functions[i] = (function(str){ return function(d){ return d[str]; }; })(functions[i]);
}
i++;
}
//return composition of functions
return function(d) {
var i=0, l = functions.length;
while (i++ < l) d = functions[i-1].call(this, d);
return d;
};
}
f.not = function(d){ return !d; };
f.run = function(d){ return d(); };
f.objToFn = function(obj, defaultVal){
if (arguments.length == 1) defaultVal = undefined;
return function(str){
return typeof(obj[str]) !== 'undefined' ? obj[str] : defaultVal;
};
};
var st = function(name, value) {
if (typeof(name) == 'object'){
for (var key in name){
addStyle(this, key, name[key]);
}
return this;
} else {
return arguments.length == 1 ? this.style(name) : addStyle(this, name, value);
}
function addStyle(sel, style, value){
style = style.replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase();
var pxStyles = 'top left bottom right padding-top padding-left padding-bottom padding-right border-top b-width border-left-width border-botto-width m border-right-width margin-top margin-left margin-bottom margin-right font-size width stroke-width line-height margin padding border border-radius max-width min-width max-height min-height';
if (~pxStyles.indexOf(style) ){
sel.style(style, typeof value == 'function' ? wrapPx(value) : addPx(value));
} else{
sel.style(style, value);
}
return sel;
}
function addPx(d){ return d.match ? d : d + 'px'; }
function wrapPx(fn){
return function(){
var val = fn.apply(this, arguments);
return addPx(val)
}
}
};
// while this might not be reprentative for all fonts, it is
// still better than assuming every character has the same width
// (set monospace=true if you want to bypass this)
var CHAR_W = {
A:7,a:7,B:8,b:7,C:8,c:6,D:9,d:7,E:7,e:7,F:7,f:4,G:9,g:7,H:9,h:7,I:3,i:3,J:5,j:3,K:8,k:6,L:7,l:3,M:11,
m:11,N:9,n:7,O:9,o:7,P:8,p:7,Q:9,q:7,R:8,r:4,S:8,s:6,T:7,t:4,U:9,u:7,V:7,v:6,W:11,w:9,X:7,x:6,Y:7,y:6,Z:7,z:5,
'.':2,',':2,':':2,';':2
};
var wordwrap = function(line, maxCharactersPerLine, minCharactersPerLine, monospace) {
var l, lines = [], w = [], words = [], w1, maxChars, minChars, maxLineW, minLineW;
w1 = line.split(' ');
w1.forEach(function(s, i) {
var w2 = s.split('-');
var lw = (i < w1.length - 1 ? ' ' : '');
if (w2.length > 1) {
w2.forEach(function(t, j) {
w.push(t + (j < w2.length - 1 ? '-' : lw));
});
} else {
w.push(s + lw);
}
});
maxChars = maxCharactersPerLine || 40;
minChars = minCharactersPerLine || Math.max(3, Math.min(maxChars * 0.5, 0.75 * w.map(word_len).sort(num_asc)[Math.round(w.length / 2)]));
maxLineW = maxChars * CHAR_W.a;
minLineW = minChars * CHAR_W.a;
l = 0;
w.forEach(function(d) {
var ww = d3Array.sum(d.split('').map(char_w));
if (l + ww > maxLineW && l > minLineW) {
lines.push(words.join(''));
words.length = 0;
l = 0;
}
l += ww;
return words.push(d);
});
if (words.length) {
lines.push(words.join(''));
}
return lines.filter(function(d) {
return d !== '';
});
function char_w(c) { return !monospace && CHAR_W[c] || CHAR_W.a; }
function word_len(d) { return d.length; }
function num_asc(a, b) { return a - b; }
};
var ascendingKey = function(key) {
return typeof key == 'function' ? function (a, b) {
return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : key(a) >= key(b) ? 0 : NaN;
} : function (a, b) {
return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : a[key] >= b[key] ? 0 : NaN;
};
};
var descendingKey = function(key) {
return typeof key == 'function' ? function (a, b) {
return key(b) < key(a) ? -1 : key(b) > key(a) ? 1 : key(b) >= key(a) ? 0 : NaN;
} : function (a, b) {
return b[key] < a[key] ? -1 : b[key] > a[key] ? 1 : b[key] >= a[key] ? 0 : NaN;
};
};
var conventions = function(c){
c = c || {};
c.margin = c.margin || {}
;['top', 'right', 'bottom', 'left'].forEach(function(d){
if (!c.margin[d] && c.margin[d] !== 0) c.margin[d] = 20 ;
});
if (c.parentSel) c.sel = c.parentSel; // backwords comp
var node = c.sel && c.sel.node();
c.totalWidth = c.totalWidth || node && node.offsetWidth || 960;
c.totalHeight = c.totalHeight || node && node.offsetHeight || 500;
c.width = c.width || c.totalWidth - c.margin.left - c.margin.right;
c.height = c.height || c.totalHeight - c.margin.top - c.margin.bottom;
c.totalWidth = c.width + c.margin.left + c.margin.right;
c.totalHeight = c.height + c.margin.top + c.margin.bottom;
c.sel = c.sel || d3Selection.select('body');
c.sel.st({position: 'relative', height: c.totalHeight, width: c.totalWidth});
c.x = c.x || d3Scale.scaleLinear().range([0, c.width]);
c.y = c.y || d3Scale.scaleLinear().range([c.height, 0]);
c.xAxis = c.xAxis || d3Axis.axisBottom().scale(c.x);
c.yAxis = c.yAxis || d3Axis.axisLeft().scale(c.y);
c.layers = (c.layers || 's').split('').map(function(type){
var layer;
if (type == 's'){
layer = c.sel.append('svg')
.st({position: c.layers ? 'absolute' : ''})
.attr('width', c.totalWidth)
.attr('height', c.totalHeight)
.append('g')
.attr('transform', 'translate(' + c.margin.left + ',' + c.margin.top + ')');
if (!c.svg) c.svg = layer; // defaults to lowest svg layer
} else if (type == 'c'){
var s = window.devicePixelRatio || 1;
layer = c.sel.append('canvas')
.at({width: c.totalWidth*s, height: c.totalHeight*s})
.st({width: c.totalWidth, height: c.totalHeight})
.st({position: 'absolute'})
.node().getContext('2d');
layer.scale(s, s);
layer.translate(c.margin.left, c.margin.top);
} else if (type == 'd'){
layer = c.sel.append('div')
.st({
position: 'absolute',
left: c.margin.left,
top: c.margin.top,
width: c.width,
height: c.height
});
}
return layer
});
return c;
};
var drawAxis = function(c){
var xAxisSel = c.svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + c.height + ')')
.call(c.xAxis);
var yAxisSel = c.svg.append('g')
.attr('class', 'y axis')
.call(c.yAxis);
return {xAxisSel: xAxisSel, yAxisSel: yAxisSel}
};
var clamp = function(min, d, max) {
return Math.max(min, Math.min(max, d))
};
var attachTooltip = function(sel, tooltipSel, fieldFns){
if (!sel.size()) return;
tooltipSel = tooltipSel || d3Selection.select('.tooltip');
sel
.on('mouseover.attachTooltip', ttDisplay)
.on('mousemove.attachTooltip', ttMove)
.on('mouseout.attachTooltip', ttHide)
.on('click.attachTooltip', function(d){ console.log(d); });
var d = sel.datum();
fieldFns = fieldFns || d3Collection.keys(d)
.filter(function(str){
return (typeof d[str] != 'object') && (d[str] != 'array');
})
.map(function(str){
return function(d){ return str + ': <b>' + d[str] + '</b>'; };
});
function ttDisplay(d){
tooltipSel
.classed('tooltip-hidden', false)
.html('')
.appendMany('div', fieldFns)
.html(function(fn){ return fn(d); });
d3Selection.select(this).classed('tooltipped', true);
}
function ttMove(d){
if (!tooltipSel.size()) return;
var e = d3Selection.event,
x = e.clientX,
y = e.clientY,
bb = tooltipSel.node().getBoundingClientRect(),
left = clamp(20, (x-bb.width/2), window.innerWidth - bb.width - 20),
top = innerHeight > y + 20 + bb.height ? y + 20 : y - bb.height - 20;
tooltipSel
.style('left', left +'px')
.style('top', top + 'px');
}
function ttHide(d){
tooltipSel.classed('tooltip-hidden', true);
d3Selection.selectAll('.tooltipped').classed('tooltipped', false);
}
};
var loadData = function(){
var q = d3Queue.queue();
var args = [].slice.call(arguments);
var files = args.slice(0, args.length - 1);
var cb = args[args.length - 1];
files.forEach(function(d){
var type = d.split('?')[0].split('.').reverse()[0];
var loadFn = {csv: d3Request.csv, tsv: d3Request.tsv, json: d3Request.json}[type];
if (!loadFn) return cb(new Error('Invalid type', d));
q.defer(loadFn, d) ;
});
q.awaitAll(cb);
};
var nestBy = function(array, key){
return d3Collection.nest().key(key).entries(array).map(function(d){
d.values.key = d.key;
return d.values;
});
};
var round = function(n, p) {
return p ? Math.round(n * (p = Math.pow(10, p))) / p : Math.round(n);
};
// Clips the specified subject polygon to the specified clip polygon;
// requires the clip polygon to be counterclockwise and convex.
// https://en.wikipedia.org/wiki/Sutherland鈥揌odgman_algorithm
var polygonClip = function(clip, subject) {
var input,
closed = polygonClosed(subject),
i = -1,
n = clip.length - polygonClosed(clip),
j,
m,
a = clip[n - 1],
b,
c,
d;
while (++i < n) {
input = subject.slice();
subject.length = 0;
b = clip[i];
c = input[(m = input.length - closed) - 1];
j = -1;
while (++j < m) {
d = input[j];
if (polygonInside(d, a, b)) {
if (!polygonInside(c, a, b)) {
subject.push(polygonIntersect(c, d, a, b));
}
subject.push(d);
} else if (polygonInside(c, a, b)) {
subject.push(polygonIntersect(c, d, a, b));
}
c = d;
}
if (closed) subject.push(subject[0]);
a = b;
}
return subject;
};
function polygonInside(p, a, b) {
return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
}
// Intersect two infinite lines cd and ab.
function polygonIntersect(c, d, a, b) {
var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3,
y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3,
ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
return [x1 + ua * x21, y1 + ua * y21];
}
// Returns true if the polygon is closed.
function polygonClosed(coordinates) {
var a = coordinates[0],
b = coordinates[coordinates.length - 1];
return !(a[0] - b[0] || a[1] - b[1]);
}
var prev = {};
var timer$1 = function(fn, delay, time, name){
if (prev[name]) prev[name].stop();
var newTimer = d3Timer.timer(fn, delay, time, name);
if (name) prev[name] = newTimer;
return newTimer
};
var prev$1 = {};
var interval$1 = function(fn, delay, time, name){
if (prev$1[name]) prev$1[name].stop();
var newTimer = d3Timer.interval(fn, delay, time, name);
if (name) prev$1[name] = newTimer;
return newTimer
};
var prev$2 = {};
var timeout$1 = function(fn, delay, time, name){
if (prev$2[name]) prev$2[name].stop();
var newTimer = d3Timer.timeout(fn, delay, time, name);
if (name) prev$2[name] = newTimer;
return newTimer
};
d3Selection.selection.prototype.translate = translateSelection;
d3Transition.transition.prototype.translate = translateSelection;
d3Selection.selection.prototype.append = append;
d3Selection.selection.prototype.insert = insert;
d3Selection.selection.prototype.parent = parent;
d3Selection.selection.prototype.selectAppend = selectAppend;
d3Selection.selection.prototype.tspans = tspans;
d3Selection.selection.prototype.appendMany = appendMany;
d3Selection.selection.prototype.at = at;
d3Selection.selection.prototype.st = st;
d3Transition.transition.prototype.at = at;
d3Transition.transition.prototype.st = st;
d3Selection.selection.prototype.prop = d3Selection.selection.prototype.property;
exports.wordwrap = wordwrap;
exports.parseAttributes = parseAttributes;
exports.f = f;
exports.ascendingKey = ascendingKey;
exports.descendingKey = descendingKey;
exports.conventions = conventions;
exports.drawAxis = drawAxis;
exports.attachTooltip = attachTooltip;
exports.loadData = loadData;
exports.nestBy = nestBy;
exports.round = round;
exports.clamp = clamp;
exports.polygonClip = polygonClip;
exports.timer = timer$1;
exports.interval = interval$1;
exports.timeout = timeout$1;
Object.defineProperty(exports, '__esModule', { value: true });
})));