This repository has been archived by the owner on Nov 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathgdp.js
672 lines (567 loc) · 16.8 KB
/
gdp.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
(function() {
'use strict';
// local alias for region id => name lookups
var REGION_ID_NAME = eiti.data.REGION_ID_NAME;
var colorscheme = colorbrewer.Purples;
// our state is immutable!
var state = new Immutable.Map();
var rendered = false;
// this flag indicates whether we're in the middle of a state mutation
var mutating = false;
// create references for often-used elements
var root = d3.select('#gdp');
var regionSections = root.selectAll('.regions > .region');
var timeline = root.select('#timeline');
var getter = eiti.data.getter; // getter("foo")({foo: 1}) === 1
var formatDollars = eiti.format.dollars;
var formatPercent = d3.format('%.2');
var formatNumber = formatDollars;
var NULL_FILL = '#eee';
// buttons that expand and collapse other elements
var filterToggle = root.select('button.toggle-filters');
// FIXME: componentize these too
root.selectAll('a[data-key]')
.on('click', function() {
d3.event.preventDefault();
});
// get the filters and add change event handlers
var filters = root.selectAll('.filters [name]')
// intialize the state props
.each(function() {
state = state.set(this.name, this.value);
})
.on('change', function() {
if (mutating) {
// console.warn('change while mutating');
return;
}
var prop = this.name;
var value = this.value;
mutateState(function(state) {
return state.set(prop, value);
});
});
// create our data "model"
var model = createModel();
// kick off the "app"
initialize();
// when the hash changes, update the state
d3.select(window)
.on('hashchange', function() {
if (mutating) {
return;
}
var props = parseHash();
mutateState(function() {
return new Immutable.Map(props);
});
});
function initialize() {
var props = parseHash();
if (Object.keys(props).length) {
filterToggle.attr('aria-expanded', true);
}
return mutateState(function(state) {
return state.merge(props);
}) || render(state);
}
function parseHash() {
if (!location.hash) {
return {};
}
var hash = location.hash.substr(1);
return eiti.url.qs.parse(hash);
}
function mutateState(fn) {
mutating = true;
var old = state;
state = fn(state);
if (!Immutable.is(old, state)) {
render(state, old);
location.hash = eiti.url.qs.format(state.toJS());
mutating = false;
return true;
}
mutating = false;
return false;
}
function render(state, previous) {
// console.time('render');
// update the filters
filters.each(function() {
this.value = state.get(this.name) || '';
});
formatNumber = state.get('units') === 'percent'
? formatPercent
: formatDollars;
var region = state.get('region') || 'US';
var selected = regionSections
.classed('active', function() {
return this.id === region;
})
.filter('.active');
updateFilterDescription(state);
model.on('yearly', function(data) {
timeline.call(updateTimeline, data, state);
});
selected.call(renderRegion, state);
// console.timeEnd('render');
rendered = true;
}
function renderRegion(selection, state) {
var regionId = state.get('region') || 'US';
var fields = getFields(state);
// console.log('loading', regionId);
// console.time('load');
model.load(state, function(error, data) {
// console.timeEnd('load');
if (error) {
console.warn('error:', error.status, error.statusText);
data = [];
}
// console.time('render regions');
var header = selection.select('.region-header');
if (header.select('tr').empty()) {
header.append('tr')
.call(createRegionRow);
}
var first = data[0];
var value = getter(fields.value);
header
.datum({
data: first,
value: first.Value,
share: first.Share, // XXX
properties: {
name: regionId === 'US' ? 'Nationwide' : 'Total'
}
})
.call(updateRegionRow, true);
var map = selection.select('[is="eiti-map"]');
onMapLoaded(map, function() {
var subregions = map.selectAll('path.feature');
switch (regionId) {
case 'US':
subregions.on('click.mutate', eventMutator('region', 'id'));
break;
}
var features = subregions.data();
var dataByFeatureId = d3.nest()
.key(getter(fields.region))
.rollup(function(d) {
return d[0];
})
.map(data);
// console.log('data by feature id:', dataByFeatureId);
var featureId = getter(fields.featureId);
features.forEach(function(f) {
var id = featureId(f);
var d = dataByFeatureId[id];
f.data = d;
f.value = d ? d.Value : undefined;
f.share = d ? d.Share : undefined; // XXX
});
var percent = state.get('units') === 'percent';
var value = getter(percent ? 'share' : 'value');
var values = features.map(value);
var scale = createScale(values, state);
subregions.style('fill', function(d) {
var v = value(d);
return v === undefined
? NULL_FILL
: scale(v);
});
selection.select('.map-legend')
.call(updateLegend, scale);
selection
.call(updateSubregions, features, scale);
// console.timeEnd('render regions');
});
});
}
function onMapLoaded(map, fn) {
if (map.property('loaded')) {
return fn.apply(map.node(), map.datum());
}
return map.on('load', function() {
fn.apply(this, arguments);
});
}
function updateSubregions(selection, features, scale) {
var list = selection.select('.subregions tbody');
if (list.empty()) {
// console.warn('no subregions list:', selection.node());
return;
}
features = features.filter(function(d) {
return !!d.value;
});
var items = list.selectAll('tr.subregion')
.data(features, getter('id'));
items.exit().remove();
var enter = items.enter()
.append('tr')
.call(createRegionRow);
var key = state.get('units') === 'percent'
? 'share'
: 'value';
items.sort(function(a, b) {
return d3.descending(a[key], b[key]);
});
items.select('.color-swatch')
.style('background-color', function(d) {
return scale(d.value);
});
items.call(updateRegionRow);
}
function createRegionRow(selection) {
selection
.attr('class', 'subregion');
var title = selection.append('td')
.attr('class', 'subregion-name');
title.append('span')
.attr('class', 'color-swatch');
title.append('span')
.attr('class', 'text');
selection.append('td')
.attr('class', 'value value_dollars');
selection.append('td')
.attr('class', 'bar bar_dollars')
.append('eiti-bar');
selection.append('td')
.attr('class', 'value value_share');
selection.append('td')
.attr('class', 'bar bar_share')
.append('eiti-bar')
.attr('max', 1);
}
function updateRegionRow(selection, isHeader) {
selection.select('.subregion-name .text')
.text(function(f) {
// XXX all features need a name!
return f.properties.name || '(' + f.id + ')';
});
var value = getter('value');
var values = selection.data()
.map(value)
.sort(d3.ascending);
var max = d3.max(values.map(Math.abs));
selection.select('.value_dollars')
.text(function(d) {
return formatDollars(d.value);
});
selection.select('.bar_dollars eiti-bar')
.attr('max', max)
.attr('value', value);
selection.select('.value_share')
.text(function(d) {
return formatPercent(d.share);
});
selection.select('.bar_share eiti-bar')
.attr('value', getter('share'));
}
function createScale(values, state) {
if (state.get('units') === 'percent') {
return d3.scale.quantize()
.domain([0, 1])
.range(colorscheme[5]);
}
var extent = d3.extent(values);
var min = extent[0];
var max = Math.max(extent[1], 0);
var colors = colorscheme;
if (max >= 2e9) {
colors = colors[7];
} else if (max >= 1e6) {
colors = colors[5];
} else {
colors = colors[3];
}
var domain = (min < 0)
? [Math.min(min, 0), max]
: [0, max];
domain = d3.scale.linear()
.domain(domain)
.nice()
.domain();
return d3.scale.quantize()
.domain(domain)
.range(colors);
}
function updateLegend(legend, scale) {
var domain = scale.domain();
if (domain.some(isNaN)) {
legend.classed('legend-invalid', true);
return;
}
legend.classed('legend-invalid', false);
var data = scale.range().map(function(y) {
return {
color: y,
range: scale.invertExtent(y)
};
});
data.unshift({
color: NULL_FILL,
range: ['no data'],
none: true
});
var last = data.length - 1;
var steps = legend.selectAll('.step')
.data(data);
steps.exit().remove();
steps.enter().append('div')
.attr('class', 'step')
.append('span')
.attr('class', 'label');
steps
.style('border-color', getter('color'))
.select('.label')
.text(function(d, i) {
return d.none
? d.range[0]
: i === last
? formatNumber(d.range[0]) + '+'
: formatNumber(d.range[0]);
});
}
function getFields(state) {
var fields = {
region: 'Region',
value: state.get('units') === 'percent'
? 'Share'
: 'Value',
featureId: 'id'
};
return fields;
}
function updateTimeline(selection, data, state) {
var fields = getFields(state);
var value = getter(fields.value);
var dataByYearPolarity = d3.nest()
.key(function(d) {
return value(d) < 0 ? 'negative' : 'positive';
})
.key(getter('Year'))
.rollup(function(d) {
return d3.sum(d, value);
})
.map(data);
// console.log('data by year/polarity:', dataByYearPolarity);
var positiveYears = dataByYearPolarity.positive || {};
var positiveExtent = d3.extent(d3.values(positiveYears));
var negativeYears = dataByYearPolarity.negative || {};
var negativeExtent = d3.extent(d3.values(negativeYears));
// get the slider to determine the year range
var slider = root.select('#year-selector').node();
// XXX: d3.range() is exclusive, so we need to add two
// in order to include the last year *and* make the area render the right
// edge of the last year.
var years = d3.range(slider.min, slider.max + 2, 1);
var w = 500;
var h = 40;
var viewBox = selection.attr('viewBox');
// if there is a viewBox already, derive the dimensions from it
if (viewBox) {
viewBox = viewBox.split(' ').map(Number);
w = viewBox[2];
h = viewBox[3];
} else {
// otherwise, set up the viewBox with our default dimensions
selection.attr('viewBox', [0, 0, w, h].join(' '));
}
var left = 0; // XXX need to make room for axis labels
var right = w;
// the x-axis scale
var x = d3.scale.linear()
.domain(d3.extent(years))
.range([left, right + 2]);
// the y-axis domain sets a specific point for zero.
// the `|| -100` and `|| 100` bits here ensure that the domain has some
// size, even if there is no data from which to derive an extent.
var yDomain = [
negativeExtent[0] || 0,
positiveExtent[1] || 100
];
// the y-axis scale, with the zero point at 3/4 the height
// XXX: note that this exaggerates the negative scale!
var y = d3.scale.linear()
.domain(yDomain)
.range([h, 0]);
var area = d3.svg.area()
.interpolate('step-after')
.x(function(d) { return x(d.year); })
.y0(y(0))
.y1(function(d) { return y(d.value); });
var areas = selection.selectAll('path.area')
.data([
{
polarity: 'positive',
values: years.map(function(year) {
return {
year: year,
value: positiveYears[year] || 0
};
})
},
{
polarity: 'negative',
values: years.map(function(year) {
return {
year: year,
value: negativeYears[year] || 0
};
})
}
]);
areas.exit().remove();
areas.enter().append('path')
.attr('class', function(d) {
return 'area ' + d.polarity;
});
var zero = selection.select('g.zero');
if (zero.empty()) {
zero = selection.append('g')
.attr('class', 'zero');
zero.append('line');
zero.append('text')
.attr('class', 'label')
.attr('text-anchor', 'end')
.attr('dy', 0.5);
// .text(0);
}
var mask = selection.select('g.mask');
if (mask.empty()) {
mask = selection.append('g')
.attr('class', 'mask');
mask.append('rect')
.attr('class', 'before')
.attr('x', 0)
.attr('width', 0)
.attr('height', h);
mask.append('rect')
.attr('class', 'after')
.attr('x', w)
.attr('width', w)
.attr('height', h);
mask.append('line')
.attr('class', 'before')
.attr('y1', 0)
.attr('y2', h);
mask.append('line')
.attr('class', 'after')
.attr('y1', 0)
.attr('y2', h);
}
var updated = selection.property('updated');
var t = function(d) { return d; };
if (updated) {
t = function(d) {
return d.transition()
.duration(500);
};
}
var year1 = slider.value;
var year2 = slider.value + 1;
var beforeX = x(year1);
var afterX = Math.min(x(year2), w);
// don't transition these
mask.select('rect.before')
.attr('width', beforeX);
mask.select('rect.after')
.attr('x', afterX);
mask.select('line.before')
.attr('transform', 'translate(' + [beforeX, 0] + ')');
mask.select('line.after')
.attr('transform', 'translate(' + [afterX, 0] + ')');
// transition these
// mask = t(mask);
mask.selectAll('line')
.attr('y1', y(positiveYears[year1] || 0))
.attr('y2', y(negativeYears[year1] || 0));
zero.select('line')
.attr('x1', left)
.attr('x2', right);
zero.select('.label')
.attr('transform', 'translate(' + [left, 0] + ')');
t(zero).attr('transform', 'translate(' + [0, y(0)] + ')');
t(areas).attr('d', function(d) {
return area(d.values);
});
selection.property('updated', true);
}
function createModel() {
var model = {};
var dispatch = d3.dispatch('yearly');
var req;
model.load = function(state, done) {
if (req) {
req.abort();
}
var url = getDataURL(state);
// console.log('model.load():', url);
req = eiti.load(url, function(error, data) {
if (error) {
data = [];
}
applyFilters(data, state, done);
});
return req;
};
function getDataURL(state) {
return eiti.data.path + 'gdp/regional.tsv';
}
function applyFilters(data, state, done) {
// coerce strings to numbers
data.forEach(function(d) {
d.Value = +d.Value;
d.Share = +d.Share;
});
// console.log('applying filters:', state.toJS());
var region = state.get('region');
if (region) {
var fields = getFields(state);
var getRegion = getter(fields.region);
data = data.filter(function(d) {
return getRegion(d) === region;
});
}
dispatch.yearly(data);
var year = state.get('year');
if (year) {
data = data.filter(function(d) {
// XXX jshint ignore
return d.Year == year;
});
}
return done(null, data);
}
return d3.rebind(model, dispatch, 'on');
}
function updateFilterDescription(state) {
var desc = root.select('#filter-description');
var data = {
region: REGION_ID_NAME[state.get('region') || 'US'],
year: state.get('year')
};
desc.selectAll('[data-key]')
.text(function() {
return data[this.getAttribute('data-key')];
});
}
function eventMutator(destProp, sourceKey) {
sourceKey = getter(sourceKey);
return function(d) {
var value = sourceKey(d);
mutateState(function(state) {
return state.set(destProp, value);
});
d3.event.preventDefault();
};
}
function stateChanged(old, state, key) {
var prev = old.get(key) || '';
var next = state.get(key) || '';
return prev !== next;
}
})(this);