-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-original.js
532 lines (460 loc) · 14.7 KB
/
index-original.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
const domTools = require('./src/domtools')
const intervalTools = require('./src/intervals')
const dataImporter = require('./src/dataimport')
const colors = require('./src/colors')
window.colors = colors
const plotly = require('plotly.js/dist/plotly')
const d3 = plotly.d3
let graphholder = d3.select('#graphholder')
window.onresize = function() { plotly.Plots.resize(graphholder.node()) }
// --------------------------------------------------------
function debugMsg(msg, level) {
level = level || 3
if (level > 1) {
console.log('DEBUG' + level + ': ' + msg)
}
}
// --------------------------------------------------------
function prepareForm() {
debugMsg('entering prepareForm', 2)
// handle dataset change
const siteSel = document.querySelector('#graph-instance .site-selector')
siteSel.addEventListener('change', function(e) {
siteSelected()
})
// handle resolution change
const setSel = document.querySelector('#graph-instance .set-selector')
setSel.addEventListener('change', function(e) {
datasetSelected()
})
// handle interval change
const intSel = document.querySelector('#graph-instance .int-selector')
intSel.addEventListener('change', function(e) {
intSelected()
})
}
// --------------------------------------------------------
function populateSiteSelector(sites) {
debugMsg('entering populateSiteSelector', 2)
const sel = document.querySelector('#graph-instance .site-selector')
// empty the selector
sel.innerHTML = ''
// add a "nothing selected" option
sel.add(new Option('select a site...', '', true))
// add an option for each dataset
sites.forEach(function(site) {
sel.add(new Option(site.name, site.id))
}.bind(this))
// un-disable the selector's parent fieldset
let fieldsetParent = domTools.findParent(sel, 'fieldset')
domTools.removeClass(fieldsetParent, 'disabled')
// // if there's just one site option, click it now
// if (sites.length === 1) {
// domTools.selectOption(sel, sites[0].id)
// domTools.addClass(fieldsetParent, 'hidden')
// }
}
// --------------------------------------------------------
function siteSelected() {
debugMsg('entering siteSelected', 2)
const sel = document.querySelector('#graph-instance .site-selector')
const siteid = sel.value
current.site = sites.filter(function(site) {return site.id === siteid })[0]
// make sure the "select a site" thing is disabled now
sel.options.item(0).disabled = true
clearGraphs()
clearDownload()
populateDatasetSelector(current.site.datasets)
clearIntervalSelector()
clearFieldSelector()
}
// --------------------------------------------------------
function populateDatasetSelector(datasets) {
debugMsg('entering populateDatasetSelector', 2)
const sel = document.querySelector('#graph-instance .set-selector')
sel.innerHTML = ''
sel.add(new Option('select a dataset...', '', true))
// add an option for each resolution
datasets.forEach(function(ds) {
sel.add(new Option(ds.name, ds.id))
})
let fieldsetParent = domTools.findParent(sel, 'fieldset')
domTools.removeClass(fieldsetParent, 'disabled')
}
// --------------------------------------------------------
function datasetSelected() {
debugMsg('entering datasetSelected', 2)
const sel = document.querySelector('#graph-instance .set-selector')
const setid = sel.value
current.dataset = current.site.datasets.filter(function(set) { return set.id === setid })[0]
// make sure the "select a dataset" thing is disabled now
sel.options.item(0).disabled = true
populateIntervalSelector(current.dataset)
populateFieldSelector(current.dataset)
}
// --------------------------------------------------------
function clearIntervalSelector(dataset) {
debugMsg('entering clearIntervalSelector', 2)
const lab = document.querySelector('#graph-instance .int-label')
const sel = document.querySelector('#graph-instance .int-selector')
sel.innerHTML = ''
domTools.addClass(lab, 'hidden')
}
// --------------------------------------------------------
function populateIntervalSelector(dataset) {
debugMsg('entering populateIntervalSelector', 2)
const lab = document.querySelector('#graph-instance .int-label')
const sel = document.querySelector('#graph-instance .int-selector')
sel.innerHTML = ''
if (dataset.period === 'all') {
// if there's no intervals, clean up then bail out
current.date = (new Date).toISOString()
domTools.addClass(lab, 'hidden')
loadDataAndMakeGraphs()
return
}
//
// so there's intervals for the user to choose from.
// Let's make a list of them.
//
const start = dataset.elements.reduce(
function(first, elem) { return intervalTools.earliest(first, elem.start) },
new Date('9999-12-31')
)
const end = dataset.elements.reduce(
function(last, elem) { return intervalTools.latest(last, (elem.end || new Date())) },
new Date('0000-01-01')
)
const intervals = intervalTools.listDates(start, end, dataset.period)
// add an option for each interval
intervals.forEach(function(int) {
sel.add(new Option(intervalTools.intervalName(int, dataset.period), int))
})
domTools.selectOption(sel, intervals[intervals.length - 1])
domTools.removeClass(lab, 'hidden')
}
// --------------------------------------------------------
function intSelected() {
debugMsg('entering intSelected', 2)
const sel = document.querySelector('#graph-instance .int-selector')
current.date = sel.value
loadDataAndMakeGraphs()
}
// --------------------------------------------------------
function clearFieldSelector() {
debugMsg('entering clearFieldSelector', 2)
const fs = document.querySelector('#graph-instance .field-selectors')
fs.innerHTML = ''
domTools.addClass(fs, 'hidden')
}
// --------------------------------------------------------
function populateFieldSelector(dataset) {
debugMsg('entering populateFieldSelector', 2)
const fs = document.querySelector('#graph-instance .field-selectors')
fs.innerHTML = ''
const crel = document.createElement.bind(document) // save typing
const crtx = document.createTextNode.bind(document) // save typing
if (dataset.defaultgraph) {
current.graph = dataset.defaultgraph.sort()
} else {
current.graph = dataset.elements.map(function(e) { return e.id })
}
dataset.elements.forEach( function(f) {
const label = crel('label')
const checkbox = crel('input')
checkbox.type = 'checkbox'
checkbox.value = f.id
checkbox.checked = (current.graph.indexOf(f.id) !== -1)
label.appendChild(checkbox)
label.appendChild(crtx(f.name))
fs.appendChild(label)
checkbox.addEventListener('change', function(e) {
fieldSelected()
})
})
domTools.removeClass(fs, 'hidden')
}
// --------------------------------------------------------
function fieldSelected() {
debugMsg('entering fieldSelected', 2)
const fs = document.querySelector('#graph-instance .field-selectors')
const fields = fs.querySelectorAll('input[type=checkbox]:checked')
current.graph = Array.apply(0, fields).map(function(f){ return f.value }).sort()
drawGraphs()
}
// --------------------------------------------------------
function showLoading(message) {
debugMsg('entering showLoading', 2)
message = message || 'loading'
const fs = document.querySelector('#graph-instance .loading')
fs.innerHTML = message
domTools.removeClass(fs, 'clear')
setTimeout( function() { fs.innerHTML = message }, 1000)
}
// --------------------------------------------------------
function clearLoading() {
debugMsg('entering clearLoading', 2)
const fs = document.querySelector('#graph-instance .loading')
domTools.addClass(fs, 'clear')
setTimeout( function() { fs.innerHTML = '' }, 1000)
}
// --------------------------------------------------------
function showDownload() {
debugMsg('entering showDownload', 2)
const lab = document.querySelector('#graph-instance .download-label')
const dl = document.querySelector('#graph-instance .download-link')
dl.href = dataImporter.datasetUrl(current.site, current.dataset, current.date)
domTools.removeClass(lab, 'hidden')
}
// --------------------------------------------------------
function clearDownload() {
debugMsg('entering clearDownload', 2)
const lab = document.querySelector('#graph-instance .download-label')
const dl = document.querySelector('#graph-instance .download-link')
dl.href = ''
domTools.addClass(lab, 'hidden')
}
// --------------------------------------------------------
function clearGraphs() {
debugMsg('entering clearGraphs', 2)
// clear out the graph hholding div
graphholder.node().innerHTML = ''
}
// --------------------------------------------------------
function loadDataAndMakeGraphs() {
debugMsg('entering loadDataAndMakeGraphs', 2)
showLoading('loading data')
showDownload()
let dataLoadProcess = dataImporter.loadDataset(
current.site, current.dataset, current.date
).then(function(data) {
current.data = data
clearLoading()
}).catch(function(err) {
const dataDesc = [
current.site.id,
current.dataset.id,
intervalTools.intervalName(current.date, current.dataset.period)
].join(' / ')
current.data = null
alert('\nThere was a problem!\n\n'
+ 'Data for ' + dataDesc + ' is not available.'
)
clearLoading()
})
current.loadProcess = dataLoadProcess
drawGraphs()
}
// --------------------------------------------------------
function drawGraphs() {
debugMsg('entering drawGraphs', 2)
clearGraphs()
// can only graph when everything is loaded..
current.loadProcess.then( function() {
const ds = current.dataset // just for typing convenience
fields = current.graph // selected fields
// get all the subgraphs ready -- if there are
// fields that share an axis type, they will share
// a single subgraph.
sgIndex = 1
let subgraphs = {}
let traces = []
// also, while we're looping through fields,
// keep track of the latest date we've seen
let latestDate = '1800-01-01'
console.log("fields")
console.log(fields)
console.log("current.data")
console.log(current.data)
fields.forEach( function(f) {
latestDate = intervalTools.latest(latestDate, current.data.time[current.data.time.length - 1])
// okay now get the field
let field = ds.elements.find( function(c) { return c.id === f }.bind(this) )
// make sure there's a subgraph for it
if (!subgraphs[field.axis]) {
let sg = { index: sgIndex, layoutFields: [] }
if (sgIndex > 1) {
sg.layoutFields.push(['xaxis' + sgIndex, { anchor: 'y' + sgIndex }])
}
sg.layoutFields.push(['yaxis' + sgIndex, {
showspikes: true,
spikethickness: 1,
spikedash: 'dot',
title: field.axis.replace(' (', '<br>(')
}])
// sg.layoutFields.push(['title', field.axis])
subgraphs[field.axis] = sg
sgIndex += 1
}
// now describe the trace for this field
traces.push({
x: current.data.time,
y: current.data[f],
name: field.name,
connectgaps: true,
type: 'scatter',
// type: 'scattergl',
mode: 'line',
line: {
color: colors.pickColor(f),
width: 2
},
xaxis: 'x',
yaxis: 'y' + subgraphs[field.axis].index
})
}.bind(this))
//
// now we've prepped data as necessary.. get the
// layout stuff ready.
//
// buttons for setting the range
const rangeButtons = ds.intervals.map( function(i) {
return intervalTools.toRangeSelector(i)
})
const startingRange = [
intervalTools.windBack(latestDate, ds.intervals[0]),
latestDate.toDate()
]
let layout = {
legend: {
orientation: 'h',
xanchor: 'center',
tracegroupgap: 20,
x: 0.5,
y: 1.1
},
xaxis: {
showspikes: true,
spikethickness: 1,
spikedash: 'dot',
anchor: 'y',
rangeselector: {
y: -0.1,
x: 1,
xanchor: 'right',
yanchor: 'top',
buttons: rangeButtons
},
rangeslider: {
autorange: true,
thickness: 0.05,
bgcolor: '#def'
},
range: startingRange,
type: 'date'
},
margin: { t:40, b:40 }
}
const width = 1 / (sgIndex-1)
const gap = 0.066
Object.values(subgraphs).forEach( function(g) {
g.layoutFields.forEach( function(lf) {
layout[lf[0]] = lf[1]
// add the domain
if (lf[0].startsWith('yaxis')) {
layout[lf[0]].domain = [
(g.index-1) * width + gap,
g.index * width
]
}
})
})
const options = {
displaylogo: false,
modeBarButtonsToRemove: [
'hoverClosestCartesian',
'hoverCompareCartesian',
'toggleSpikelines'
]
}
plotly.newPlot(
graphholder.node(),
traces,
layout,
options
)
})
}
// --------------------------------------------------------
function makeStackOfGraphs() {
debugMsg('entering makeStackOfGraphs', 2)
// clearGraphs()
// // can only graph when everything is loaded..
// current.loadProcess.then( ()=> {
// // graph all fields..
// let fields = current.dataset.elements.map( e => e.id )
// // ..unless they specify a defaultgraph field list
// if ('defaultgraph' in current.dataset) {
// console.log('default supplied...')
// fields = current.dataset.defaultgraph
// }
// console.log(fields)
// let graphs = {}
// // turn the field list into a graph list, which
// // might mean several fields get drawn into the same
// // graph (if their axes are the same)
// fields.forEach( (f) => {
// let field = current.dataset.elements.find( c => c.id === f )
// if (!graphs[field.axis]) {
// let latestDate = current.data.time[current.data.time.length - 1]
// graphs[field.axis] = {
// data: [],
// layout: {
// xaxis: {
// range: [
// intervalTools.windBack(latestDate, current.interval),
// latestDate
// ],
// rangeslider: { autorange: true },
// type: 'date'
// },
// yaxis: { title: field.axis },
// margin: { t:50, b:50 }
// }
// }
// }
// graphs[field.axis].data.push({
// x: current.data.time,
// y: current.data[f],
// mode: 'lines',
// line: { color: colors.pickColor(field.id) }
// })
// })
// Object.values(graphs).forEach( (g)=> {
// // new div for each graph
// let graphDiv = document.createElement('div')
// graphholder.node().appendChild(graphDiv)
// plotly.newPlot(graphDiv, g.data, g.layout, {displayModeBar: false})
// })
// })
}
// --------------------------------------------------------
// --------------------------------------------------------
prepareForm()
clearLoading()
let sites = []
const emptyPromise = new Promise(function(resolve) { resolve(false) } )
let current = {
loadProcess: emptyPromise,
site: null,
dataset: null,
interval: null,
date: null,
graph: [],
data: null
}
showLoading('discovering datasets')
importProcess = dataImporter.getDataInfo().then(function(siteList) {
// succeed
sites = siteList
populateSiteSelector(sites)
clearLoading()
}.bind(this), function(error) {
// fail
alert('\nThere was a problem!'
+ '\n\nTried fetching information about datasets but could not find it.'
+ '\nReload this page to try again.\n\n'
+ error
)
clearLoading()
}.bind(this))