-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
525 lines (440 loc) · 19.8 KB
/
app.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
(function() {
const state = {};
var city_1 = "friedrichshafen";
var city_2 = "lindau";
var active_city = city_1;
var inactive_city = city_2;
var active_score = 0;
var inactive_score = 0;
var scored = d3.set();
d3.selectAll("button.select_active_city")
.on("click",function(d){
if(this.id == city_1){
active_city = city_1;
inactive_city = city_2;
} else {
inactive_city = city_1;
active_city = city_2;
}
//show not initial screen items and hide selection elements
d3.selectAll(".not_initial_screen").style('display','block');
d3.selectAll(".select_active_city").style('display','none');
//draw graphs
drawGraphs();
});
const get_period = function(maxYear) {
if (active_city == city_1){
return [{year: 2014, class: 'black', title: "OB Andreas\nBrand (parteilos)"},
{year: Math.min(2018, maxYear), class: 'black', title: "OB Andreas\nBrand (parteilos)"}];
} else {
return [{year: 2012, class: 'black', title: "OB Petra\nSeidl (parteilos)"},
{year: 2014, class: 'black', title: "OB Gerhard\nEcker (SPD)"},
{year: Math.min(2018, maxYear), class: 'black', title: "OB Gerhard\nEcker (SPD)"}];
};
};
const drawGraphs = function () {
d3.selectAll('.you-draw-it').each(function () {
d3.selectAll(".active_city_label").text(active_city)
d3.selectAll(".inactive_city_label").text(inactive_city)
const sel = d3.select(this);
const key = this.dataset.key;
window.ydi_data[key].active_city;
const question = window.ydi_data[key];
const indexedData = question[active_city];
const inactiveData = question[inactive_city];
const data = Object.keys(indexedData).map(key => {
return {
year: Number(key),
value: indexedData[key]
}
});
const inactive_data = Object.keys(inactiveData).map(key => {
return {
year: Number(key),
value: inactiveData[key]
}
});
if(!state[key]) {
state[key] = {};
}
if (data.length < 1) {
console.log("No data available for:", key);
return;
}
const isMobile = window.innerWidth < 760;
const minYear = data[0].year;
const maxYear = data[data.length - 1].year;
const periods = get_period(maxYear);
const medianYear = periods[periods.length - 2].year;
const minY = Math.min(d3.min(data, d => d.value),d3.min(inactive_data, d => d.value));
const maxY = Math.max(d3.max(data, d => d.value),d3.max(inactive_data, d => d.value));
const segmentBorders = [minYear].concat(periods.map(d => d.year));
const ƒ = function () {
const functions = arguments;
//convert all string arguments into field accessors
for (var i = 0; i < functions.length; i++) {
if (typeof(functions[i]) === 'string' || typeof(functions[i]) === 'number') {
functions[i] = (str => function (d) {
return d[str];
})(functions[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
}
};
const drawAxis = function (c) {
c.axis.append('g')
.attr("class", "x axis")
.attr("transform", "translate(0," + c.height + ")")
.call(c.xAxis);
// Null-Linie
if(graphMinY < 0) {
c.axis.append('g')
.classed('nullaxis', true)
.attr("transform", "translate(0," + c.y(0) + ")")
.call(
d3.axisBottom(c.x)
.tickValues([])
.tickSize(0)
);
}
// null auf y-achse
c.axis.append('text')
.text("0")
.attr("class", "yachse")
.attr('transform', "translate(-15, " + (c.y(0)+0) + ")");
};
const formatValue = function(val, defaultPrecision) {
const data = question.precision ?
Number(val).toFixed(question.precision) :
defaultPrecision ? Number(val).toFixed(defaultPrecision) : val;
return String(data).replace('.', ',') + (question.unit ? ' ' + question.unit : '');
};
const makeLabel = function (pos, addClass) {
const x = c.x(pos);
const y = c.y(indexedData[pos]);
const text = formatValue(indexedData[pos]);
const label = c.labels.append('div')
.classed('data-label', true)
.classed(addClass, true)
.style('left', x + 'px')
.style('top', y + 'px');
label.append('span')
.text(text);
if (pos == minYear && isMobile) {
label.classed('edge-left', true);
}
if (pos == maxYear && isMobile) {
label.classed('edge-right', true);
}
return [
c.dots.append('circle')
.attr('r', 4.5)
.attr('cx', x)
.attr('cy', y)
.attr('class', addClass),
label
];
};
const drawChart = function (lower, upper, addClass) {
const definedFn = (d, i) => d.year >= lower && d.year <= upper;
const line = d3.area().x(ƒ('year', c.x)).y(ƒ('value', c.y)).defined(definedFn);
if (lower == minYear) {
makeLabel(minYear, addClass);
}
const svgClass = addClass + (upper == medianYear ? " median" : '');
const group = c.charts.append('g');
group.append('path').attr('d', line(data)).attr('class', 'line ' + svgClass);
return [
group,
].concat(makeLabel(upper, svgClass));
};
const clamp = function (a, b, c) {
return Math.max(a, Math.min(b, c))
};
// make visual area empty
sel.html('');
const margin = {
top: 20,
right: isMobile ? 20 : 50,
bottom: 20,
left: isMobile ? 20 : 50
};
const width = sel.node().offsetWidth;
const height = 400;
const c = {
width: width - (margin.left + margin.right),
height: height - (margin.top + margin.bottom)
};
// configure scales
const graphMinY = Math.min(minY, 0);
const graphMaxY = Math.max(indexedData[medianYear] * 2, maxY + (maxY - graphMinY) * 0.4); // add 40% for segment titles
c.x = d3.scaleLinear().range([0, c.width]);
c.x.domain([minYear, maxYear]);
c.y = d3.scaleLinear().range([c.height, 0]);
c.y.domain([graphMinY, graphMaxY]);
c.svg = sel.append('svg')
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("width", c.width)
.attr("height", c.height);
//append inactive charts first...
c.inactive_charts = c.svg.append('g');
// gradients
c.defs = d3.select(c.svg.node().parentNode).append('defs');
['black', 'red'].forEach(color => {
const gradient = c.defs.append('linearGradient')
.attr('id', 'gradient-' + color)
.attr('x1', '0%')
.attr('y1', '0%')
.attr('x2', '0%')
.attr('y2', '100%');
gradient.append('stop').attr('offset', '0%').attr('class', 'start');
gradient.append('stop').attr('offset', '100%').attr('class', 'end');
});
c.defs.append('marker')
.attr('id', 'preview-arrow')
.attr('orient', 'auto')
.attr('markerWidth', 2)
.attr('markerHeight', 4)
.attr('refX', 0.1)
.attr('refY', 2)
.append('path')
.attr('d', 'M0,0 V4 L2,2 Z');
// make background grid
c.grid = c.svg.append('g')
.attr('class', 'grid');
c.grid.append('g').attr('class', 'horizontal').call(
d3.axisBottom(c.x)
.tickValues(c.x.ticks(maxYear - minYear))
.tickFormat("")
.tickSize(c.height)
)
.selectAll('line')
.attr('class', (d, i) => segmentBorders.indexOf(d) !== -1 ? 'highlight' : '');
c.grid.append('g').attr('class', 'vertical').call(
d3.axisLeft(c.y)
.tickValues(c.y.ticks(6))
.tickFormat("")
.tickSize(-c.width)
);
const applyMargin = function (sel) {
sel.style('left', margin.left + 'px')
.style('top', margin.top + 'px')
.style('width', c.width + 'px')
.style('height', c.height + 'px');
};
// invisible rect for dragging to work
const dragArea = c.svg.append('rect')
.attr('class', 'draggable')
.attr('x', c.x(medianYear))
.attr('width', c.x(maxYear) - c.x(medianYear))
.attr('height', c.height)
.attr('opacity', 0);
setTimeout(() => {
const clientRect = c.svg.node().getBoundingClientRect();
c.top = clientRect.top + window.scrollY;
c.bottom = clientRect.bottom + window.scrollY;
}, 1000);
c.labels = sel.append('div')
.attr('class', 'labels')
.call(applyMargin);
c.axis = c.svg.append('g');
c.charts = c.svg.append('g');
// add a preview line
c.preview = c.svg.append('line')
.attr('class', 'preview-line')
.attr('marker-end', 'url(#preview-arrow)')
.attr('x1', c.x(medianYear))
.attr('y1', c.y(indexedData[medianYear]))
.attr('x2', c.x(medianYear) + 50)
.attr('y2', c.y(indexedData[medianYear]));
const userSel = c.svg.append('path').attr('class', 'your-line');
c.dots = c.svg.append('g').attr('class', 'dots');
// configure axes
c.xAxis = d3.axisBottom().scale(c.x);
c.xAxis.tickFormat(d => "'" + String(d).substr(2)).ticks(maxYear - minYear);
drawAxis(c);
c.titles = sel.append('div')
.attr('class', 'titles')
.call(applyMargin);
c.controls = sel.append('div')
.attr('class', 'controls')
.call(applyMargin)
.style('padding-left', c.x(medianYear) + 'px');
c.controls.append('div')
.attr('class', 'box')
.text('Linie ergänzen');
// make chart
const charts = periods.map((entry, key) => {
const lower = key > 0 ? periods[key - 1].year : minYear;
const upper = entry.year;
// segment title
c.titles.append('span')
.style('left', c.x(lower) + 'px')
.style('width', c.x(upper) - c.x(lower) + 'px')
.text(entry.title);
return drawChart(lower, upper, entry.class);
});
//define and add one inactive line and area first
const inactive_line = d3.area().x(ƒ('year', c.x)).y(ƒ('value', c.y));
const inactive_area = d3.area().x(ƒ('year', c.x)).y0(ƒ('value', c.y)).y1(c.height);
const inactive = c.inactive_charts.append('g');
inactive.append('path').attr('d', inactive_area(inactive_data)).attr('class', 'area').attr('fill', `url(#gradient-black)`);
inactive.append('path').attr('d', inactive_line(inactive_data)).attr('class', 'inactive_line black');
inactive.append('text').attr('x',20).attr('y',c.height-20).text(inactive_city.toUpperCase()).attr('class',"inactive_text");
inactive.append('rect').attr('x',0).attr('y',0).attr('width',c.width).attr('height',c.height).attr('fill','white').attr('class',"inactive"+key)
//now add results charts
const resultChart = charts[charts.length - 1][0];
const resultClip = c.charts.append('clipPath')
.attr('id', `result-clip-${key}`)
.append('rect')
.attr('width', c.x(medianYear))
.attr('height', c.height);
const resultLabel = charts[charts.length - 1].slice(1, 3);
resultChart.attr('clip-path', `url(#result-clip-${key})`)
.append('rect')
.attr('width', c.width)
.attr('height', c.height)
.attr('fill', 'none');
resultLabel.map(e => e.style('opacity', 0));
/**
* Interactive user selection part
*/
const userLine = d3.line().x(ƒ('year', c.x)).y(ƒ('value', c.y));
if(!state[key].yourData) {
state[key].yourData = data.map(d => ({year: d.year, value: indexedData[medianYear], defined: 0}))
.filter(d => {
if (d.year == medianYear) d.defined = true;
return d.year >= medianYear
});
}
const resultSection = d3.select('.result.' + key);
const drawUserLine = function() {
console.log(state[key].yourData);
userSel.attr('d', userLine.defined(ƒ('defined'))(state[key].yourData));
const d = state[key].yourData[state[key].yourData.length-1];
if(!d.defined) {
return;
}
const yourResult = c.labels.selectAll('.your-result')
.data([d]);
yourResult.enter()
.append('div')
.classed('data-label your-result', true)
.classed('edge-right', isMobile)
.merge(yourResult)
.style('left', () => c.x(maxYear) + 'px')
.style('top', r => c.y(r.value) + 'px')
.html('')
.append('span')
.text(r => formatValue(r.value, 2));
};
drawUserLine();
const interactionHandler = function() {
if (state[key].resultShown) {
return;
}
sel.node().classList.add('drawn');
const pos = d3.mouse(c.svg.node());
const year = clamp(medianYear, maxYear, c.x.invert(pos[0]));
const value = clamp(c.y.domain()[0], c.y.domain()[1], c.y.invert(pos[1]));
state[key].yourData.forEach(d => {
if(d.year > medianYear) {
if(Math.abs(d.year - year) < .5) {
d.value = value;
}
if(d.year - year < 0.5) {
d.defined = true
}
}
});
drawUserLine();
if (!state[key].compvared && d3.mean(state[key].yourData, ƒ('defined')) == 1) {
state[key].compvared = true;
resultSection.node().classList.add('finished');
resultSection.select('button').node().removeAttribute('disabled');
}
};
c.svg.call(d3.drag().on('drag', interactionHandler));
c.svg.on('click', interactionHandler);
const showResultChart = function () {
if(!state[key].compvared) {
return;
}
state[key].resultShown = true;
//set transitions to 0
var duration = 0;
if(scored.values().indexOf(key) == -1) {
duration = 700;
if(question.winner == active_city){
active_score += 1;
} else if(question.winner == inactive_city){
inactive_score += 1;
} else {
};
};
resultClip.transition()
.duration(duration)
.attr('width', c.x(maxYear));
//transition for interactive chart
d3.selectAll(".inactive" + key)
.transition()
.delay(duration)
.duration(duration*3)
.attr("x",c.width)
.attr("width",0);
//add score to set (no duplicates)
scored.add(key);
//build score string.
var score_str = active_city.toUpperCase() + " " + active_score + " : " + inactive_city.toUpperCase() + " " + inactive_score;
//update relevant score label
d3.select("#score_label"+key).text(score_str);
//if the last one, update final score
if(scored.values().length == d3.selectAll('.you-draw-it')._groups[0].length){
d3.select("#final_score").html("<h3>Endergebnis:</h3>" + "<p class='score_final'><strong>" + score_str + "</strong></p>" + "<hr class='final_score_hr'>")
};
dragArea.attr('class', '');
setTimeout(() => {
resultLabel.map(e => e.style('opacity', 1));
resultSection.node().classList.add('shown');
}, 700);
};
resultSection.select('button').on('click', showResultChart);
if(state[key].resultShown) {
showResultChart();
}
sel.on('mousemove', () => {
const pos = d3.mouse(c.svg.node());
const y = Math.min(Math.max(pos[1], c.y(graphMaxY)), c.y(graphMinY));
c.preview.attr('y2', y);
});
});
};
document.addEventListener("DOMContentLoaded", () => {
setCity();
});
const debounce = function (func, wait, immediate) {
var timeout;
return function () {
const context = this, args = arguments;
const later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
window.addEventListener('resize', debounce(() => {
drawGraphs();
}, 500));
})();