Blame view

web/static/js/main.js 52.4 KB
db69e5a7   Goutte   Continue implemen...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// ES6
//
//

/**
 *
 * All the javascript code for canvases is in this file,
 * and inline scripts in templates, such as in `home.html.jinja2` contain the
 * DOM listeners (the UI stuff, not the business logic, which is here).
 *
 * Note: We use Promises and ES6.
 *
 * D3.js
 * -----
 *
 * You also WILL NEED d3js v4 documentation : https://d3js.org/
 * We're using a custom build of 4.9.1, one line changed, see d3-custom.js
 * Event bubbling cannot trigger two rects unless we make an event dispatcher,
 * and d3's brush is stopping propagation, as it should by default.
4bbc0e4a   Goutte   Continue THE GREA...
20
 *
db69e5a7   Goutte   Continue implemen...
21
22
23
24
25
 *
 * Code is weird, with ref$
 * ------------------------
 *
 * Lots of machine-generated micro-optimizations. Most are unconsequential.
db69e5a7   Goutte   Continue implemen...
26
27
 */

8d4f8bc2   Goutte   More fixes toward...
28
(function () {
db69e5a7   Goutte   Continue implemen...
29
    const global = typeof exports !== 'undefined' && exports || this;
60522cb2   Goutte   Clean up a litle.
30
    const GOLDEN_RATIO = 2 / (1 + Math.sqrt(5)); // 0.618…
326b749d   Goutte   Finally, a decent...
31
    const RATIO = GOLDEN_RATIO ** 4; // Y/X aspect ratio of the time series
4bbc0e4a   Goutte   Continue THE GREA...
32
33
34

    class Target {
        constructor(slug, name, config) {
8d4f8bc2   Goutte   More fixes toward...
35
36
37
38
            this.slug = slug;
            this.name = name;
            this.config = config;
            this.active = this.config.active;
5a7474a9   Goutte   Lebab the livescr...
39
        }
4bbc0e4a   Goutte   Continue THE GREA...
40
    }
5a7474a9   Goutte   Lebab the livescr...
41

4bbc0e4a   Goutte   Continue THE GREA...
42
    // global.SpaceWeather = ((() => {
8d4f8bc2   Goutte   More fixes toward...
43
44
        // "The main app, instanciated from an inline script.\nIt defaults to an interval starting two months ago, and ending in a month.\n(both at midnight)";
        // SpaceWeather.displayName = 'SpaceWeather';
8d4f8bc2   Goutte   More fixes toward...
45
46
        // const prototype = SpaceWeather.prototype;
        // const constructor = SpaceWeather;
8d4f8bc2   Goutte   More fixes toward...
47

4bbc0e4a   Goutte   Continue THE GREA...
48
49
    const API_TIME_FORMAT = "YYYY-MM-DDTHH:mm:ss";
    const INPUT_TIME_FORMAT = "YYYY-MM-DD";
8d4f8bc2   Goutte   More fixes toward...
50

4bbc0e4a   Goutte   Continue THE GREA...
51
    class SpaceWeather {
60522cb2   Goutte   Clean up a litle.
52
53
54
55
56
57
        /**
         * The main app, instantiated from an inline script.
         * It defaults to an interval starting two months ago,
         * and ending in a month. (both at midnight)
         * @param configuration
         */
4bbc0e4a   Goutte   Continue THE GREA...
58
59
60
61
62
        constructor(configuration) {
            const that = this;
            this.configuration = configuration;
            this.parameters = {};
            this.targets = {};
60522cb2   Goutte   Clean up a litle.
63
64
65
66
67
68
69
70
71
72
73
74
75
            console.info("©2017\n" +
                "  _   _      _ _       ____\n" +
                " | | | | ___| (_) ___ |  _ \\ _ __ ___  _ __   __ _\n" +
                " | |_| |/ _ \\ | |/ _ \\| |_) | '__/ _ \\| '_ \\ / _` |\n" +
                " |  _  |  __/ | | (_) |  __/| | | (_) | |_) | (_| |\n" +
                " |_| |_|\\___|_|_|\\___/|_|_  |_|_ \\___/| .__/ \\__,_|\n" +
                " | |__  _   _   / ___|  _ \\|  _ \\|  _ \\_|\n" +
                " | '_ \\| | | | | |   | | | | |_) | |_) |\n" +
                " | |_) | |_| | | |___| |_| |  __/|  __/\n" +
                " |_.__/ \\__, |  \\____|____/|_|   |_|\n" +
                "        |___/\n\n" +
                "The full source of this website is available at :\n" +
                "https://gitlab.irap.omp.eu/CDPP/SPACEWEATHERONLINE");
8d4f8bc2   Goutte   More fixes toward...
76

4bbc0e4a   Goutte   Continue THE GREA...
77
78
79
            let targets_configs = [];
            for (let k in this.configuration.targets) {
                targets_configs.push(this.configuration.targets[k]);
8d4f8bc2   Goutte   More fixes toward...
80
            }
4bbc0e4a   Goutte   Continue THE GREA...
81
            targets_configs.forEach(tc => that.addTarget(new Target(tc.slug, tc.name, tc)));
8d4f8bc2   Goutte   More fixes toward...
82

4bbc0e4a   Goutte   Continue THE GREA...
83
84
85
86
            this.configuration['parameters'].forEach(p => that.parameters[p['id']] = p);
            this.orbits = null;
            this.time_series = [];
        }
8d4f8bc2   Goutte   More fixes toward...
87

56d84302   Goutte   Continue the grea...
88
89
90
91
92
93
94
95
        /**
         * This is called by the inline bootstrap javascript code.
         * This ain't in the constructor because it might return a Promise later on.
         * (for the loader, for example)
         *
         * @param started_at string
         * @param stopped_at string
         */
4bbc0e4a   Goutte   Continue THE GREA...
96
        init(started_at, stopped_at) {
1185f353   Goutte   Fix the CME Catal...
97
            const app = this;
56d84302   Goutte   Continue the grea...
98
99
100

            started_at = moment(started_at).utc().hours(0).minutes(0).seconds(0);
            stopped_at = moment(stopped_at).utc().hours(0).minutes(0).seconds(0);
4bbc0e4a   Goutte   Continue THE GREA...
101
102
            this.setStartAndStop(started_at, stopped_at);
            this.loadAndCreatePlots(started_at, stopped_at);
1185f353   Goutte   Fix the CME Catal...
103
            window.addEventListener('resize', () => app.resize());
56d84302   Goutte   Continue the grea...
104

4bbc0e4a   Goutte   Continue THE GREA...
105
106
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
107

4bbc0e4a   Goutte   Continue THE GREA...
108
109
110
111
112
113
        buildDataUrlForTarget(target_slug, started_at, stopped_at) {
            let url;
            url = this.configuration['api']['data_for_interval'];
            url = url.replace('<target>', target_slug);
            url = url.replace('<started_at>', started_at);
            url = url.replace('<stopped_at>', stopped_at);
56d84302   Goutte   Continue the grea...
114

4bbc0e4a   Goutte   Continue THE GREA...
115
116
            return url;
        }
8d4f8bc2   Goutte   More fixes toward...
117

4bbc0e4a   Goutte   Continue THE GREA...
118
119
120
121
122
123
124
125
126
        buildDownloadUrl() {
            let ref$;
            let started_at;
            let stopped_at;
            let targets;
            let t;
            let url;
            ref$ = this.getDomain(), started_at = ref$[0], stopped_at = ref$[1];
            targets = (function () {
8d4f8bc2   Goutte   More fixes toward...
127
                const results$ = [];
4bbc0e4a   Goutte   Continue THE GREA...
128
129
130
                for (t in this.targets) {
                    if (this.targets[t].active) {
                        results$.push(t);
8d4f8bc2   Goutte   More fixes toward...
131
132
133
                    }
                }
                return results$;
4bbc0e4a   Goutte   Continue THE GREA...
134
135
136
137
138
139
140
            }.call(this)).sort().join('-');
            url = this.configuration['api']['download'];
            url = url.replace('<targets>', targets);
            url = url.replace('<started_at>', started_at.format(API_TIME_FORMAT));
            url = url.replace('<stopped_at>', stopped_at.format(API_TIME_FORMAT));
            return url;
        }
8d4f8bc2   Goutte   More fixes toward...
141

4bbc0e4a   Goutte   Continue THE GREA...
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
        buildSampUrl() {
            let ref$;
            let started_at;
            let stopped_at;
            let targets;
            let t;
            let parameters;
            let p;
            let url;
            ref$ = this.getDomain(), started_at = ref$[0], stopped_at = ref$[1];
            targets = (function () {
                const results$ = [];
                for (t in this.targets) {
                    if (this.targets[t].active) {
                        results$.push(t);
8d4f8bc2   Goutte   More fixes toward...
157
                    }
8d4f8bc2   Goutte   More fixes toward...
158
                }
4bbc0e4a   Goutte   Continue THE GREA...
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
                return results$;
            }.call(this)).sort().join('-');
            parameters = (function () {
                const results$ = [];
                for (p in this.parameters) {
                    if (this.parameters[p].active) {
                        results$.push(p);
                    }
                }
                return results$;
            }.call(this)).sort().join('-');
            url = this.configuration['api']['samp'];
            url = url.replace('<targets>', targets);
            url = url.replace('<params>', parameters);
            url = url.replace('<started_at>', started_at.format(API_TIME_FORMAT));
            url = url.replace('<stopped_at>', stopped_at.format(API_TIME_FORMAT));
            return url;
        }
5a7474a9   Goutte   Lebab the livescr...
177

4bbc0e4a   Goutte   Continue THE GREA...
178
179
180
181
182
183
184
185
186
        buildSampName() {
            let ref$;
            let started_at;
            let stopped_at;
            let targets;
            let t;
            ref$ = this.getDomain(), started_at = ref$[0], stopped_at = ref$[1];
            targets = (function () {
                let i$;
8d4f8bc2   Goutte   More fixes toward...
187
                let ref$;
4bbc0e4a   Goutte   Continue THE GREA...
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
                let len$;
                const results$ = [];
                for (i$ = 0, len$ = (ref$ = this.getEnabledTargets()).length; i$ < len$; ++i$) {
                    t = ref$[i$];
                    results$.push(t.name);
                }
                return results$;
            }.call(this)).sort().join(', ');
            return `Heliopropa for ${targets} from ${started_at.format(API_TIME_FORMAT)} to ${stopped_at.format(API_TIME_FORMAT)}.`;
        }

        addTarget(target) {
            this.targets[target.slug] = target;
            return this;
        }

        getEnabledTargets() {
            let slug;
            let ref$;
            let target;
            const results$ = [];
            for (slug in ref$ = this.targets) {
                target = ref$[slug];
                if (target.active) {
                    results$.push(target);
8d4f8bc2   Goutte   More fixes toward...
213
                }
8d4f8bc2   Goutte   More fixes toward...
214
            }
4bbc0e4a   Goutte   Continue THE GREA...
215
216
            return results$;
        }
5a7474a9   Goutte   Lebab the livescr...
217

4bbc0e4a   Goutte   Continue THE GREA...
218
219
220
221
222
223
        enableTarget(target_slug) {
            let ref$;
            const this$ = this;
            this.time_series.forEach(ts => {
                if (ts.target.slug === target_slug && this$.parameters[ts.parameter].active) {
                    return ts.show();
8d4f8bc2   Goutte   More fixes toward...
224
                }
4bbc0e4a   Goutte   Continue THE GREA...
225
226
227
228
            });
            this.targets[target_slug].active = true;
            if ((ref$ = this.orbits) != null) {
                ref$.enableTarget(target_slug);
8d4f8bc2   Goutte   More fixes toward...
229
            }
4bbc0e4a   Goutte   Continue THE GREA...
230
231
            return this;
        }
5a7474a9   Goutte   Lebab the livescr...
232

4bbc0e4a   Goutte   Continue THE GREA...
233
234
235
236
237
238
239
240
241
242
        disableTarget(target_slug) {
            let ref$;
            this.time_series.forEach(ts => {
                if (ts.target.slug === target_slug) {
                    return ts.hide();
                }
            });
            this.targets[target_slug].active = false;
            if ((ref$ = this.orbits) != null) {
                ref$.disableTarget(target_slug);
8d4f8bc2   Goutte   More fixes toward...
243
            }
4bbc0e4a   Goutte   Continue THE GREA...
244
245
            return this;
        }
5a7474a9   Goutte   Lebab the livescr...
246

4bbc0e4a   Goutte   Continue THE GREA...
247
        resize() {
1185f353   Goutte   Fix the CME Catal...
248
249
            if (null != this.orbits) {
                this.orbits.resize();
8d4f8bc2   Goutte   More fixes toward...
250
            }
4bbc0e4a   Goutte   Continue THE GREA...
251
252
253
            this.time_series.forEach(ts => ts.resize());
            return this;
        }
5a7474a9   Goutte   Lebab the livescr...
254

4bbc0e4a   Goutte   Continue THE GREA...
255
256
257
258
259
260
261
262
        showLoader() {
            return $('#plots_loader').show();
        }

        hideLoader() {
            return $('#plots_loader').hide();
        }

326b749d   Goutte   Finally, a decent...
263
264
265
266
267
268
269
270
271
        /**
         * Load the data as CSV for the specified target and interval,
         * and return it in a Promise.
         *
         * @param target_slug
         * @param started_at
         * @param stopped_at
         * @returns {Promise<any>}
         */
4bbc0e4a   Goutte   Continue THE GREA...
272
        loadData(target_slug, started_at, stopped_at) {
326b749d   Goutte   Finally, a decent...
273
            let app = this;
4bbc0e4a   Goutte   Continue THE GREA...
274
            return new Promise((resolve, reject) => {
326b749d   Goutte   Finally, a decent...
275
                let url = app.buildDataUrlForTarget(target_slug, started_at, stopped_at);
4bbc0e4a   Goutte   Continue THE GREA...
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
                return d3.csv(url, csv => {
                    let timeFormat;
                    let data;
                    console.debug(`Requested CSV for ${target_slug}…`, csv);
                    timeFormat = d3.utcParse('%Y-%m-%dT%H:%M:%S%Z');
                    data = {
                        'hee': []
                    };
                    configuration['parameters'].forEach(parameter => data[parameter['id']] = []);
                    if (!csv) {
                        reject('invalid');
                    }
                    if (!csv.length) {
                        reject('empty');
                    }
                    csv.forEach(d => {
                        let dtime;
                        dtime = timeFormat(d['time']);
                        configuration['parameters'].forEach(parameter => {
                            let id;
                            let val;
                            id = parameter['id'];
                            val = parseFloat(d[id]);
                            if (!isNaN(val)) {
                                return data[id].push({
                                    x: dtime,
                                    y: val
8d4f8bc2   Goutte   More fixes toward...
303
304
305
                                });
                            }
                        });
4bbc0e4a   Goutte   Continue THE GREA...
306
307
308
309
310
311
312
                        if (d['xhee'] && d['yhee']) {
                            return data['hee'].push({
                                t: dtime,
                                x: parseFloat(d['xhee']),
                                y: parseFloat(d['yhee'])
                            });
                        }
8d4f8bc2   Goutte   More fixes toward...
313
                    });
4bbc0e4a   Goutte   Continue THE GREA...
314
                    return resolve(data);
8d4f8bc2   Goutte   More fixes toward...
315
                });
4bbc0e4a   Goutte   Continue THE GREA...
316
317
            });
        }
8d4f8bc2   Goutte   More fixes toward...
318

56d84302   Goutte   Continue the grea...
319
320
321
322
323
324
        /**
         *
         * @param started_at moment(.js) datetime object
         * @param stopped_at moment(.js) datetime object
         * @returns {SpaceWeather}
         */
4bbc0e4a   Goutte   Continue THE GREA...
325
        loadAndCreatePlots(started_at, stopped_at) {
4bbc0e4a   Goutte   Continue THE GREA...
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
            let targets;
            let res$;
            let k;
            let handleTarget;
            const this$ = this;
            this.showLoader();
            this.started_at = started_at;
            this.stopped_at = stopped_at;
            this.orbits = new Orbits(this.configuration.orbits_container, this.configuration);
            started_at = started_at.format(API_TIME_FORMAT);
            stopped_at = stopped_at.format(API_TIME_FORMAT);
            res$ = [];
            for (k in this.targets) {
                res$.push(this.targets[k]);
            }
            targets = res$;
            targets.forEach(target => {
                let targetButton;
                targetButton = $(`.targets-filters .target.${target.slug}`);
                targetButton.addClass('loading');
                return targetButton.removeClass('failed error empty');
            });
            handleTarget = i => {
                let target;
                let targetButton;
                if (i >= targets.length) {
                    return;
8d4f8bc2   Goutte   More fixes toward...
353
                }
4bbc0e4a   Goutte   Continue THE GREA...
354
355
356
357
358
359
360
361
362
                target = targets[i];
                console.info(`Loading CSV data of ${target.name}…`);
                targetButton = $(`.targets-filters .target.${target.slug}`);
                return this$.loadData(target.slug, started_at, stopped_at).then(data => {
                    console.info(`Loaded CSV data of ${target.name}.`, data);
                    this$.createTimeSeries(target, data);
                    this$.orbits.initOrbiter(target.slug, target.config, data['hee']);
                    targetButton.removeClass('loading');
                    if (target.active) {
8d4f8bc2   Goutte   More fixes toward...
363
                        this$.hideLoader();
4bbc0e4a   Goutte   Continue THE GREA...
364
365
                    } else {
                        this$.disableTarget(target.slug);
8d4f8bc2   Goutte   More fixes toward...
366
                    }
4bbc0e4a   Goutte   Continue THE GREA...
367
368
369
370
371
372
373
374
375
376
377
378
379
                    return handleTarget(i + 1);
                }, error => {
                    let msg;
                    switch (error) {
                        case 'invalid':
                            console.error(`Failed loading CSV data of ${target.name}.`);
                            targetButton.addClass('error');
                            break;
                        case 'empty':
                            msg = `No data for ${target.name}\n during interval from \n${started_at} to ${stopped_at}.`;
                            console.warn(msg);
                            targetButton.addClass('empty');
                            break;
8d4f8bc2   Goutte   More fixes toward...
380
                    }
4bbc0e4a   Goutte   Continue THE GREA...
381
382
383
384
                    targetButton.addClass('failed');
                    targetButton.removeClass('loading');
                    this$.hideLoader();
                    return handleTarget(i + 1);
8d4f8bc2   Goutte   More fixes toward...
385
                });
4bbc0e4a   Goutte   Continue THE GREA...
386
387
388
389
            };
            handleTarget(0);
            return this;
        }
db69e5a7   Goutte   Continue implemen...
390

4bbc0e4a   Goutte   Continue THE GREA...
391
392
393
394
395
396
397
        clearPlots() {
            this.orbits.clear();
            this.time_series.forEach(ts => ts.clear());
            this.orbits = null;
            this.time_series = [];
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
398

4bbc0e4a   Goutte   Continue THE GREA...
399
        createTimeSeries(target, data) {
03452084   Goutte   Make time series'...
400
            const app = this;
4bbc0e4a   Goutte   Continue THE GREA...
401
402
403
404
            this.configuration['parameters'].forEach(parameter => {
                let container;
                let id;
                let title;
03452084   Goutte   Make time series'...
405
                container = app.configuration['time_series_container'];
4bbc0e4a   Goutte   Continue THE GREA...
406
407
408
409
410
411
412
                id = parameter['id'];
                title = parameter['title'];
                if (!(id in data)) {
                    console.error(`No data for id '${id}'.`, data);
                }
                console.log(target['name'], id, data[id]);
                if (data[id].length) {
03452084   Goutte   Make time series'...
413
414
415
                    return app.time_series.push(new TimeSeries(id, title, target, data[id], app.parameters[id].active, container, {
                        'started_at': app.started_at,
                        'stopped_at': app.stopped_at
4bbc0e4a   Goutte   Continue THE GREA...
416
                    }));
8d4f8bc2   Goutte   More fixes toward...
417
                }
4bbc0e4a   Goutte   Continue THE GREA...
418
            });
03452084   Goutte   Make time series'...
419
            this.time_series.forEach((ts, tsk) => {
4bbc0e4a   Goutte   Continue THE GREA...
420
421
                ts.options['onMouseOver'] = () => true;
                ts.options['onMouseOut'] = () => {
03452084   Goutte   Make time series'...
422
                    app.time_series.forEach(ts2 => ts2.hideCursor());
4bbc0e4a   Goutte   Continue THE GREA...
423
424
425
426
                    return true;
                };
                ts.options['onMouseMove'] = t => {
                    let ref$;
03452084   Goutte   Make time series'...
427
428
                    app.time_series.forEach(ts2 => ts2.moveCursor(t));
                    if ((ref$ = app.orbits) != null) {
4bbc0e4a   Goutte   Continue THE GREA...
429
                        ref$.moveToDate(t);
8d4f8bc2   Goutte   More fixes toward...
430
                    }
4bbc0e4a   Goutte   Continue THE GREA...
431
432
                    return true;
                };
03452084   Goutte   Make time series'...
433
434
435
436

                ts.options['onBrushEnd'] = ((sta, sto) => {
                    //console.debug('Why is this true? bind() WTF', this === app);
                    app.resizeDomain(moment(sta), moment(sto), ts);
4bbc0e4a   Goutte   Continue THE GREA...
437
                    return true;
03452084   Goutte   Make time series'...
438
439
                }).bind(ts);

1185f353   Goutte   Fix the CME Catal...
440
                ts.options['onDblClick'] = () => {
4bbc0e4a   Goutte   Continue THE GREA...
441
                    let ref$;
03452084   Goutte   Make time series'...
442
                    app.resetZoom();
4bbc0e4a   Goutte   Continue THE GREA...
443
444
445
446
447
448
449
450
                    if ((ref$ = $("#zoom_controls_help")) != null) {
                        ref$.remove();
                    }
                    return true;
                };
            });
            return this.time_series;
        }
db69e5a7   Goutte   Continue implemen...
451

4bbc0e4a   Goutte   Continue THE GREA...
452
453
454
455
456
457
458
459
460
461
462
463
464
        getEnabledParameters() {
            let i$;
            let ref$;
            let len$;
            let p;
            let slug;
            const results$ = [];
            for (i$ = 0, len$ = (ref$ = this.parameters).length; i$ < len$; ++i$) {
                p = i$;
                slug = ref$[i$];
                if (p.active) {
                    results$.push(p);
                }
8d4f8bc2   Goutte   More fixes toward...
465
466
            }

4bbc0e4a   Goutte   Continue THE GREA...
467
468
            return results$;
        }
db69e5a7   Goutte   Continue implemen...
469

4bbc0e4a   Goutte   Continue THE GREA...
470
471
472
473
        enableParameter(parameter_slug) {
            const this$ = this;
            if (!(parameter_slug in this.parameters)) {
                console.error(`Unknown parameter ${parameter_slug}.`);
8d4f8bc2   Goutte   More fixes toward...
474
            }
4bbc0e4a   Goutte   Continue THE GREA...
475
476
477
478
479
480
            this.parameters[parameter_slug].active = true;
            this.time_series.forEach(ts => {
                if (ts.parameter === parameter_slug && this$.targets[ts.target.slug].active) {
                    return ts.show();
                }
            });
8d4f8bc2   Goutte   More fixes toward...
481

4bbc0e4a   Goutte   Continue THE GREA...
482
483
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
484

4bbc0e4a   Goutte   Continue THE GREA...
485
486
487
        disableParameter(parameter_slug) {
            if (!(parameter_slug in this.parameters)) {
                console.error(`Unknown parameter ${parameter_slug}.`);
8d4f8bc2   Goutte   More fixes toward...
488
            }
4bbc0e4a   Goutte   Continue THE GREA...
489
490
491
492
            this.parameters[parameter_slug].active = false;
            this.time_series.forEach(ts => {
                if (ts.parameter === parameter_slug) {
                    return ts.hide();
8d4f8bc2   Goutte   More fixes toward...
493
                }
4bbc0e4a   Goutte   Continue THE GREA...
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
            });

            return this;
        }

        showCatalogLayer(catalog_slug) {
            this.time_series.forEach(ts => ts.showCatalogLayer(catalog_slug));
            return this;
        }

        hideCatalogLayer(catalog_slug) {
            this.time_series.forEach(ts => ts.hideCatalogLayer(catalog_slug));
            return this;
        }

        getDomain() {
            if (this.current_started_at != null && this.current_stopped_at != null) {
                return [this.current_started_at, this.current_stopped_at];
8d4f8bc2   Goutte   More fixes toward...
512
            }
4bbc0e4a   Goutte   Continue THE GREA...
513
514
            return [this.started_at, this.stopped_at];
        }
8d4f8bc2   Goutte   More fixes toward...
515

03452084   Goutte   Make time series'...
516
        resizeDomain(started_at, stopped_at, starting_ts) {
4bbc0e4a   Goutte   Continue THE GREA...
517
518
519
            let max_stopped_at;
            let formatted_started_at;
            let formatted_stopped_at;
4bbc0e4a   Goutte   Continue THE GREA...
520
521
            let zoomedOnVisible;
            if (stopped_at < started_at) {
326b749d   Goutte   Finally, a decent...
522
523
524
                let tmp_at = started_at;
                started_at = stopped_at;
                stopped_at = tmp_at;
4bbc0e4a   Goutte   Continue THE GREA...
525
526
            }
            if (started_at === stopped_at) {
326b749d   Goutte   Finally, a decent...
527
                alert("Please provide distinct start and stop dates.");
4bbc0e4a   Goutte   Continue THE GREA...
528
529
530
531
532
533
534
535
536
537
538
539
540
                return;
            }
            max_stopped_at = started_at.clone().add(2, 'years');
            if (stopped_at > max_stopped_at) {
                console.warn("The time interval was truncated because it was bigger than two years.");
                stopped_at = max_stopped_at;
            }
            this.setStartAndStop(started_at, stopped_at);
            formatted_started_at = started_at.format();
            formatted_stopped_at = stopped_at.format();
            if ((this.started_at <= started_at && started_at <= this.stopped_at) &&
                (this.started_at <= stopped_at && stopped_at <= this.stopped_at)) {
                console.info(`Resizing the temporal domain from ${formatted_started_at} to ${formatted_stopped_at} without fetching new data…`);
03452084   Goutte   Make time series'...
541
542
543
544
                let tsv = this.time_series.filter(ts => ts.visible);
                let tsv_length = tsv.length;
                let starting_ts_key = tsv.indexOf(starting_ts);
                if (starting_ts_key === -1) starting_ts_key = 0;
4bbc0e4a   Goutte   Continue THE GREA...
545
                zoomedOnVisible = new Promise((resolve, reject) => {
1185f353   Goutte   Fix the CME Catal...
546
                    console.log("Zoom on invisible time series…");
4bbc0e4a   Goutte   Continue THE GREA...
547
548
                    let tsv_zoom_on_next;
                    tsv_zoom_on_next = i => {
4bbc0e4a   Goutte   Continue THE GREA...
549
550
551
552
                        if (i >= tsv_length) {
                            resolve();
                            return;
                        }
326b749d   Goutte   Finally, a decent...
553
                        let ts;
03452084   Goutte   Make time series'...
554
                        ts = tsv[(i+starting_ts_key)%tsv_length];
4bbc0e4a   Goutte   Continue THE GREA...
555
556
557
                        ts.zoomIn(started_at, stopped_at)
                          .then(() => tsv_zoom_on_next(i + 1));
                    };
1185f353   Goutte   Fix the CME Catal...
558
                    tsv_zoom_on_next(0);
4bbc0e4a   Goutte   Continue THE GREA...
559
560
                });
                zoomedOnVisible.then(() => {
1185f353   Goutte   Fix the CME Catal...
561
                    console.log("Now zoom on invisible time series…");
4bbc0e4a   Goutte   Continue THE GREA...
562
563
564
565
                    this.time_series.forEach(ts => {
                        if (!ts.visible) {
                            ts.zoomIn(started_at, stopped_at);
                        }
8d4f8bc2   Goutte   More fixes toward...
566
                    });
4bbc0e4a   Goutte   Continue THE GREA...
567
568
569
570
571
572
573
                });
                this.orbits.resizeDomain(started_at, stopped_at);
            } else {
                console.info(`Resizing the temporal domain from ${formatted_started_at} to ${formatted_stopped_at} and fetching new data…`);
                console.warn("This might take a good while… Why not see what else we're up to on http://cdpp.eu while you're waiting?");
                this.clearPlots();
                this.loadAndCreatePlots(started_at, stopped_at);
8d4f8bc2   Goutte   More fixes toward...
574
            }
4bbc0e4a   Goutte   Continue THE GREA...
575
576
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
577

4bbc0e4a   Goutte   Continue THE GREA...
578
        resetZoom() {
03452084   Goutte   Make time series'...
579
            this.resizeDomain(this.started_at, this.stopped_at);
4bbc0e4a   Goutte   Continue THE GREA...
580
581
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
582

4bbc0e4a   Goutte   Continue THE GREA...
583
584
585
586
587
588
        setStartAndStop(started_at, stopped_at) {
            console.info(`Setting time interval from ${started_at} to ${stopped_at}…`);
            this.current_started_at = started_at;
            this.current_stopped_at = stopped_at;
            $("#started_at").val(started_at.format(INPUT_TIME_FORMAT));
            $("#stopped_at").val(stopped_at.format(INPUT_TIME_FORMAT));
db69e5a7   Goutte   Continue implemen...
589

4bbc0e4a   Goutte   Continue THE GREA...
590
            return this;
5a7474a9   Goutte   Lebab the livescr...
591
        }
4bbc0e4a   Goutte   Continue THE GREA...
592
    }
5a7474a9   Goutte   Lebab the livescr...
593

8d4f8bc2   Goutte   More fixes toward...
594
595
596
597

    /////////////////////////////////////////////////////////////////////////////
    //// TIME SERIES ////////////////////////////////////////////////////////////

4bbc0e4a   Goutte   Continue THE GREA...
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    class TimeSeries {
        constructor(parameter, title, target, data, visible, container, options) {
            this.onBrushEnd = this.onBrushEnd.bind(this);
            this.onDoubleClick = this.onDoubleClick.bind(this);
            this.onMouseOut = this.onMouseOut.bind(this);
            this.onMouseOver = this.onMouseOver.bind(this);
            this.onMouseMove = this.onMouseMove.bind(this);
            this.parameter = parameter;
            this.title = title;
            this.target = target;
            this.data = data;
            this.visible = visible;
            this.container = container;
            this.options = options || {};
            let now = moment();
            const dataLength = this.data.length;
            const predictiveData = [];
            let d;
            for (let i = 0; i < dataLength; ++i) {
                d = this.data[i];
                if (moment(d.x) >= now) {
                    predictiveData.push(d);
8d4f8bc2   Goutte   More fixes toward...
620
                }
8d4f8bc2   Goutte   More fixes toward...
621
            }
4bbc0e4a   Goutte   Continue THE GREA...
622
623
624
            this.predictiveData = predictiveData;
            this.init();
        }
8d4f8bc2   Goutte   More fixes toward...
625

4bbc0e4a   Goutte   Continue THE GREA...
626
627
628
        toString() {
            return `${this.title} of ${this.target.name}`;
        }
8d4f8bc2   Goutte   More fixes toward...
629

4bbc0e4a   Goutte   Continue THE GREA...
630
        init() {
4bbc0e4a   Goutte   Continue THE GREA...
631
632
633
634
635
636
637
638
639
640
641
642
643
644
            let clipId;
            let i$;
            let len$;
            let line;
            let lineElement;
            let dx;
            const this$ = this;
            console.info(`Initializing plot of ${this}…`);
            this.margin = {
                top: 30,
                right: 20,
                bottom: 30,
                left: 80
            };
56d84302   Goutte   Continue the grea...
645
646
647
            let dimensions = this.recomputeDimensions();
            let width  = dimensions[0];
            let height = dimensions[1];
4bbc0e4a   Goutte   Continue THE GREA...
648
649
650
651
652
653
654
655
            this.xDataExtent = d3.extent(this.data, d => d.x);
            this.yDataExtent = d3.extent(this.data, d => d.y);
            if (this.options['started_at']) {
                this.xDataExtent[0] = this.options['started_at'];
            }
            if (this.options['stopped_at']) {
                this.xDataExtent[1] = this.options['stopped_at'];
            }
326b749d   Goutte   Finally, a decent...
656
            this.xScale = d3.scaleUtc().domain(this.xDataExtent);
4bbc0e4a   Goutte   Continue THE GREA...
657
            this.yScale = d3.scaleLinear().domain(this.yDataExtent);
326b749d   Goutte   Finally, a decent...
658
659

            // http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html
56d84302   Goutte   Continue the grea...
660
661
662
663
664
665
666
667
            const formatMillisecond = d3.utcFormat(".%L");
            const formatSecond = d3.utcFormat(":%S");
            const formatMinute = d3.utcFormat("%H:%M");
            const formatHour = d3.utcFormat("%H:%M");
            const formatDay = d3.utcFormat("%a %d");
            const formatWeek = d3.utcFormat("%b %d");
            const formatMonth = d3.utcFormat("%B");
            const formatYear = d3.utcFormat("%Y");
326b749d   Goutte   Finally, a decent...
668
            const formatDoy = d3.utcFormat("%Y-%j");
56d84302   Goutte   Continue the grea...
669
            const multiFormat = date => {
326b749d   Goutte   Finally, a decent...
670
                if (date > d3.utcSecond(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
671
                    return formatMillisecond(date);
8d4f8bc2   Goutte   More fixes toward...
672
                }
326b749d   Goutte   Finally, a decent...
673
                if (date > d3.utcMinute(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
674
                    return formatSecond(date);
8d4f8bc2   Goutte   More fixes toward...
675
                }
326b749d   Goutte   Finally, a decent...
676
                if (date > d3.utcHour(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
677
678
                    return formatMinute(date);
                }
326b749d   Goutte   Finally, a decent...
679
                if (date > d3.utcDay(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
680
681
                    return formatHour(date);
                }
56d84302   Goutte   Continue the grea...
682

326b749d   Goutte   Finally, a decent...
683
684
685
686
687
688
689
690
691
692
693
694
695
                return formatDoy(date);
                // if (date > d3.utcMonth(date)) {
                //     if (date > d3.utcWeek(date)) {
                //         return utcDay(date);
                //     } else {
                //         return utcWeek(date);
                //     }
                // }
                // if (date > d3.utcYear(date)) {
                //     return formatMonth(date);
                // }
                //
                // return formatYear(date);
4bbc0e4a   Goutte   Continue THE GREA...
696
            };
326b749d   Goutte   Finally, a decent...
697

4bbc0e4a   Goutte   Continue THE GREA...
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
            this.xAxis = d3.axisBottom().tickFormat(multiFormat).ticks(7);
            this.yAxis = d3.axisLeft().ticks(10);
            this.svg = d3.select(this.container).append('svg');
            this.svg.attr("class", `${this.parameter} ${this.target.slug}`);
            this.line = d3.line().x(d => this$.xScale(d.x)).y(d => this$.yScale(d.y));
            this.plotWrapper = this.svg.append('g');
            this.plotWrapper.attr('transform', `translate(${this.margin.left},${this.margin.top})`);
            clipId = `ts-clip-${this.parameter}-${this.target.slug}`;
            this.clip = this.svg.append("defs").append("svg:clipPath").attr("id", clipId).append("svg:rect").attr("x", 0).attr("y", 0);
            this.pathWrapper = this.plotWrapper.append('g');
            this.pathWrapper.attr("clip-path", `url(#${clipId})`);
            this.path = this.pathWrapper.append('path').datum(this.data).classed('line', true);
            this.predictiveDataPath = this.pathWrapper.append('path').datum(this.predictiveData).classed('predictive-line', true);
            this.createCatalogLayers();
            this.horizontalLines = [];
            if (this.options['horizontalLines']) {
56d84302   Goutte   Continue the grea...
714
715
                for (i$ = 0, len$ = (dimensions = this.options['horizontalLines']).length; i$ < len$; ++i$) {
                    line = dimensions[i$];
4bbc0e4a   Goutte   Continue THE GREA...
716
717
718
719
720
                    lineElement = this.svg.append("line").attr("class", "line horitonal-line").style("stroke", "orange").style("stroke-dasharray", "3, 2");
                    this.horizontalLines.push({
                        'element': lineElement,
                        'config': line
                    });
8d4f8bc2   Goutte   More fixes toward...
721
                }
8d4f8bc2   Goutte   More fixes toward...
722
            }
4bbc0e4a   Goutte   Continue THE GREA...
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
            this.brush = this.plotWrapper.append("g").attr("class", "brush");
            this.plotWrapper.append('g').classed('x axis', true);
            this.plotWrapper.append('g').classed('y axis', true);
            this.yAxisText = this.plotWrapper.append("text").attr("transform", "rotate(-90)").attr("dy", "1em").style("text-anchor", "middle").text(this.title);
            this.yAxisTextTarget = this.plotWrapper.append("text").attr("transform", "rotate(-90)").attr("dy", "1em").style("text-anchor", "middle").style("font-style", "oblique").text(this.target.name);
            this.focus = this.plotWrapper.append('g').style("display", "none");
            this.cursorCircle = this.focus.append("circle").attr("class", "cursor-circle").attr("r", 3);
            dx = 8;
            this.cursorValueShadow = this.focus.append("text").attr("class", "cursor-text cursor-text-shadow").attr("dx", dx).attr("dy", "-.3em");
            this.cursorValue = this.focus.append("text").attr("class", "cursor-text cursor-value").attr("dx", dx).attr("dy", "-.3em");
            this.cursorDateShadow = this.focus.append("text").attr("class", "cursor-text cursor-text-shadow").attr("dx", dx).attr("dy", "1em");
            this.cursorDate = this.focus.append("text").attr("class", "cursor-text cursor-date").attr("dx", dx).attr("dy", "1em");
            this.brushFunction = d3.brushX().extent([[0, 0], [width, height]]).handleSize(0).on("end", this.onBrushEnd);
            this.brush.call(this.brushFunction);
            this.brushOverlay = this.svg.select(".brush .overlay");
            this.brushOverlay.on("mouseover.swapp", this.onMouseOver).on("mouseout.swapp", this.onMouseOut).on("mousemove.swapp", this.onMouseMove).on("dblclick.swapp", this.onDoubleClick);
            return this.resize();
        }
8d4f8bc2   Goutte   More fixes toward...
741

4bbc0e4a   Goutte   Continue THE GREA...
742
743
744
745
746
747
748
749
750
        recomputeDimensions() {
            let width;
            let height;
            width = Math.ceil($(this.container).width() - this.margin.left - this.margin.right);
            height = Math.ceil(RATIO * width);
            this.plotWidth = width;
            this.plotHeight = height;
            return [width, height];
        }
8d4f8bc2   Goutte   More fixes toward...
751

4bbc0e4a   Goutte   Continue THE GREA...
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
        resize() {
            let ref$;
            let width;
            let height;
            let i$;
            let len$;
            let line;
            let lineValue;
            ref$ = this.recomputeDimensions(), width = ref$[0], height = ref$[1];
            console.debug(`Resizing ${this}: ${width} x ${height}…`);
            this.xScale.range([0, width]);
            this.yScale.range([height, 0]);
            this.svg.attr('width', width + this.margin.right + this.margin.left).attr('height', height + this.margin.top + this.margin.bottom);
            this.clip.attr("width", width).attr("height", height);
            this.path.attr('d', this.line);
            this.predictiveDataPath.attr('d', this.line);
            for (i$ = 0, len$ = (ref$ = this.horizontalLines).length; i$ < len$; ++i$) {
                line = ref$[i$];
                lineValue = this.yScale(line['config']['value']) + this.margin.top;
                line['element'].attr("x1", this.margin.left).attr("y1", lineValue).attr("x2", this.margin.left + width).attr("y2", lineValue);
            }
            this.xAxis.scale(this.xScale);
            this.yAxis.scale(this.yScale);
            this.xAxis.ticks(Math.floor(width / 80.0));
            this.yAxis.ticks(Math.floor(height / 18.0));
            this.svg.select('.x.axis').attr('transform', `translate(0,${height})`).call(this.xAxis);
            this.svg.select('.y.axis').call(this.yAxis);
            this.yAxisText.attr("y", 20 - this.margin.left).attr("x", 0 - height / 2);
            this.yAxisTextTarget.attr("y", 0 - this.margin.left).attr("x", 0 - height / 2.0);
            this.resizeCatalogLayers();
            if (!this.visible) {
                this.hide();
            }
            return this;
        }

        clear() {
            $(this.svg.node()).remove();
            return this.visible = false;
        }
8d4f8bc2   Goutte   More fixes toward...
792

4bbc0e4a   Goutte   Continue THE GREA...
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        show() {
            $(this.svg.node()).show();
            return this.visible = true;
        }

        hide() {
            $(this.svg.node()).hide();
            return this.visible = false;
        }

        onMouseMove() {
            let x;
            x = this.xScale.invert(d3.mouse(this.brushOverlay.node())[0]);
            if (this.options.onMouseMove != null) {
                return this.options.onMouseMove(x);
            } else {
                return this.moveCursor(x);
8d4f8bc2   Goutte   More fixes toward...
810
            }
4bbc0e4a   Goutte   Continue THE GREA...
811
        }
8d4f8bc2   Goutte   More fixes toward...
812

4bbc0e4a   Goutte   Continue THE GREA...
813
814
815
816
817
        onMouseOver() {
            if (this.options.onMouseOver != null) {
                return this.options.onMouseOver();
            } else {
                return this.showCursor();
8d4f8bc2   Goutte   More fixes toward...
818
            }
4bbc0e4a   Goutte   Continue THE GREA...
819
        }
8d4f8bc2   Goutte   More fixes toward...
820

4bbc0e4a   Goutte   Continue THE GREA...
821
822
823
824
825
        onMouseOut() {
            if (this.options.onMouseOut != null) {
                return this.options.onMouseOut();
            } else {
                return this.hideCursor();
8d4f8bc2   Goutte   More fixes toward...
826
            }
4bbc0e4a   Goutte   Continue THE GREA...
827
        }
8d4f8bc2   Goutte   More fixes toward...
828

4bbc0e4a   Goutte   Continue THE GREA...
829
830
831
832
833
        onDoubleClick() {
            if (this.options.onDblClick != null) {
                return this.options.onDblClick();
            } else {
                return this.resetZoom();
8d4f8bc2   Goutte   More fixes toward...
834
            }
4bbc0e4a   Goutte   Continue THE GREA...
835
        }
8d4f8bc2   Goutte   More fixes toward...
836

4bbc0e4a   Goutte   Continue THE GREA...
837
        onBrushEnd() {
03452084   Goutte   Make time series'...
838
            let s = d3.event.selection;
4bbc0e4a   Goutte   Continue THE GREA...
839
            if (s) {
03452084   Goutte   Make time series'...
840
                let minmax = [s[0], s[1]].map(this.xScale.invert, this.xScale);
4bbc0e4a   Goutte   Continue THE GREA...
841
842
                this.brush.call(this.brushFunction.move, null);
                if (this.options.onBrushEnd != null) {
03452084   Goutte   Make time series'...
843
844
                    // same, the 'this' is still the old one
                    // return this.options.onBrushEnd.apply(this, [minmax[0], minmax[1]]);
4bbc0e4a   Goutte   Continue THE GREA...
845
                    return this.options.onBrushEnd(minmax[0], minmax[1]);
8d4f8bc2   Goutte   More fixes toward...
846
                } else {
4bbc0e4a   Goutte   Continue THE GREA...
847
                    return this.zoomIn(minmax[0], minmax[1]);
8d4f8bc2   Goutte   More fixes toward...
848
849
                }
            }
4bbc0e4a   Goutte   Continue THE GREA...
850
        }
8d4f8bc2   Goutte   More fixes toward...
851

4bbc0e4a   Goutte   Continue THE GREA...
852
853
854
855
856
857
858
859
        zoomIn(startDate, stopDate) {
            let ref$;
            let minDate;
            let maxDate;
            console.debug(`Zooming in ${this} from ${startDate} to ${stopDate}.`);
            ref$ = this.xDataExtent, minDate = ref$[0], maxDate = ref$[1];
            if (startDate < minDate) {
                startDate = minDate;
8d4f8bc2   Goutte   More fixes toward...
860
            }
4bbc0e4a   Goutte   Continue THE GREA...
861
862
863
864
865
            if (stopDate > maxDate) {
                stopDate = maxDate;
            }
            this.xScale.domain([startDate, stopDate]);
            this.yScale.domain(d3.extent(this.data, d => {
8d4f8bc2   Goutte   More fixes toward...
866
                let ref$;
4bbc0e4a   Goutte   Continue THE GREA...
867
868
869
870
                if (startDate <= (ref$ = d.x) && ref$ <= stopDate) {
                    return d.y;
                } else {
                    return 0;
8d4f8bc2   Goutte   More fixes toward...
871
                }
4bbc0e4a   Goutte   Continue THE GREA...
872
873
874
            }));
            return this.applyZoom();
        }
8d4f8bc2   Goutte   More fixes toward...
875

4bbc0e4a   Goutte   Continue THE GREA...
876
        applyZoom() {
1185f353   Goutte   Fix the CME Catal...
877
            let duration = 0;
4bbc0e4a   Goutte   Continue THE GREA...
878
879
880
881
            duration = 0;
            if (this.visible) {
                duration = 750;
                console.debug(`Applying zoom to visible ${this}…`);
1185f353   Goutte   Fix the CME Catal...
882
                let t = this.svg.transition().duration(duration);
4bbc0e4a   Goutte   Continue THE GREA...
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
                this.svg.select('.x.axis').transition(t).call(this.xAxis);
                this.svg.select('.y.axis').transition(t).call(this.yAxis);
                this.path.transition(t).attr('d', this.line);
                this.predictiveDataPath.transition(t).attr('d', this.line);
            } else {
                console.debug(`Applying zoom to hidden ${this}…`);
                this.svg.select('.x.axis').call(this.xAxis);
                this.svg.select('.y.axis').call(this.yAxis);
                this.path.attr('d', this.line);
                this.predictiveDataPath.attr('d', this.line);
            }
            this.resizeCatalogLayers();
            this.hideCursor();
            return new Promise((resolve, reject) => {
                if (0 === duration) {
                    return resolve();
8d4f8bc2   Goutte   More fixes toward...
899
                } else {
4bbc0e4a   Goutte   Continue THE GREA...
900
                    return setTimeout(() => resolve(), duration + 50);
8d4f8bc2   Goutte   More fixes toward...
901
                }
4bbc0e4a   Goutte   Continue THE GREA...
902
903
            });
        }
8d4f8bc2   Goutte   More fixes toward...
904

4bbc0e4a   Goutte   Continue THE GREA...
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
        createCatalogLayers() {
            let catalog_slug;
            let ref$;
            let layers;
            let i$;
            let len$;
            let layer;
            let started_at;
            let stopped_at;
            this.layers_rects = {};
            for (catalog_slug in ref$ = this.target.config.layers) {
                layers = ref$[catalog_slug];
                this.layers_rects[catalog_slug] = [];
                for (i$ = 0, len$ = layers.length; i$ < len$; ++i$) {
                    layer = layers[i$];
                    started_at = moment(layer.start);
                    stopped_at = moment(layer.stop);
                    this.layers_rects[catalog_slug].push(this.createCatalogLayer(started_at, stopped_at));
8d4f8bc2   Goutte   More fixes toward...
923
                }
4bbc0e4a   Goutte   Continue THE GREA...
924
                this.hideCatalogLayer(catalog_slug);
8d4f8bc2   Goutte   More fixes toward...
925
            }
4bbc0e4a   Goutte   Continue THE GREA...
926
927
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
928

4bbc0e4a   Goutte   Continue THE GREA...
929
930
        createCatalogLayer(started_at, stopped_at) {
            let layer_rect;
56d84302   Goutte   Continue the grea...
931
932
933
934
935
936
            layer_rect = this.pathWrapper.append("rect")
                .attr('y', 0)
                .attr('height', this.plotHeight)
                .attr('fill', '#FFFD64C2');
            //won't work, possibly because of our input catcher rect.
            //layer_rect.append('svg:title').text("!");
4bbc0e4a   Goutte   Continue THE GREA...
937
938
            return layer_rect;
        }
8d4f8bc2   Goutte   More fixes toward...
939

4bbc0e4a   Goutte   Continue THE GREA...
940
941
942
943
944
945
946
947
948
949
950
951
952
953
        resizeCatalogLayers() {
            let catalog_slug;
            let ref$;
            let layers;
            let i$;
            let len$;
            let i;
            let layer;
            let started_at;
            let stopped_at;
            let width;
            for (catalog_slug in ref$ = this.target.config.layers) {
                layers = ref$[catalog_slug];
                for (i$ = 0, len$ = layers.length; i$ < len$; ++i$) {
8d4f8bc2   Goutte   More fixes toward...
954
                    i = i$;
4bbc0e4a   Goutte   Continue THE GREA...
955
956
957
958
959
                    layer = layers[i$];
                    started_at = moment(layer.start);
                    stopped_at = moment(layer.stop);
                    width = Math.max(2, this.xScale(stopped_at) - this.xScale(started_at));
                    this.layers_rects[catalog_slug][i].attr('x', this.xScale(started_at)).attr('width', width);
8d4f8bc2   Goutte   More fixes toward...
960
                }
8d4f8bc2   Goutte   More fixes toward...
961
            }
4bbc0e4a   Goutte   Continue THE GREA...
962
963
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
964

4bbc0e4a   Goutte   Continue THE GREA...
965
966
967
968
969
970
971
972
973
974
975
976
977
        showCatalogLayer(catalog_slug) {
            let i$;
            let ref$;
            let len$;
            let i;
            let layer;
            for (i$ = 0, len$ = (ref$ = this.target.config.layers[catalog_slug]).length; i$ < len$; ++i$) {
                i = i$;
                layer = ref$[i$];
                this.layers_rects[catalog_slug][i].style("display", null);
            }
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
978

4bbc0e4a   Goutte   Continue THE GREA...
979
980
981
982
983
984
985
986
987
988
989
990
991
        hideCatalogLayer(catalog_slug) {
            let i$;
            let ref$;
            let len$;
            let i;
            let layer;
            for (i$ = 0, len$ = (ref$ = this.target.config.layers[catalog_slug]).length; i$ < len$; ++i$) {
                i = i$;
                layer = ref$[i$];
                this.layers_rects[catalog_slug][i].style("display", "none");
            }
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
992

4bbc0e4a   Goutte   Continue THE GREA...
993
994
995
        showCursor() {
            return this.focus.style("display", null);
        }
8d4f8bc2   Goutte   More fixes toward...
996

4bbc0e4a   Goutte   Continue THE GREA...
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
        hideCursor() {
            return this.focus.style("display", "none");
        }

        moveCursor(x0) {
            let i;
            let d0;
            let d1;
            let d;
            let xx;
            let yy;
            let dx;
            let transform;
            i = this.bisectDate(this.data, x0, 1);
            d0 = this.data[i - 1];
            d1 = this.data[i];
            if (!d1 || !d0) {
                this.hideCursor();
                return;
            }
            d = x0 - d0.x > d1.x - x0 ? d1 : d0;
            xx = this.xScale(d.x);
            yy = this.yScale(d.y);
            const mirrored = this.plotWidth != null && xx > this.plotWidth / 2;
            dx = 8;
            if (mirrored) {
                dx = -1 * dx;
            }
            transform = `translate(${xx}, ${yy})`;
            this.cursorCircle.attr("transform", transform);
            this.cursorValue.attr("transform", transform).text(d.y).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx);
            this.cursorValueShadow.attr("transform", transform).text(d.y).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx);
            this.cursorDate.attr("transform", transform).text(this.timeFormat(d.x)).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx);
            this.cursorDateShadow.attr("transform", transform).text(this.timeFormat(d.x)).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx);
            this.showCursor();
            return this;
5a7474a9   Goutte   Lebab the livescr...
1033
        }
4bbc0e4a   Goutte   Continue THE GREA...
1034
    }
8d4f8bc2   Goutte   More fixes toward...
1035

4bbc0e4a   Goutte   Continue THE GREA...
1036
1037
    TimeSeries.prototype.bisectDate = d3.bisector(d => d.x).left;
    TimeSeries.prototype.timeFormat = d3.utcFormat("%Y-%m-%d %H:%M");
db69e5a7   Goutte   Continue implemen...
1038
1039
1040
1041
1042


    ///////////////////////////////////////////////////////////////////////////
    //// ORBITS PLOT //////////////////////////////////////////////////////////

4bbc0e4a   Goutte   Continue THE GREA...
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
    class Orbits {
        constructor(container, options) {
            this.container = container;
            this.options = options || {};
            console.log("Initializing plot of orbits…");
            this.margin = {
                top: 30,
                right: 20,
                bottom: 42,
                left: 60
            };
            this.data = {};
            this.orbiters = {};
            this.orbitersElements = {};
            this.orbitersExtrema = {};
            this.lastOrbiterData = {};
            this.xScale = d3.scaleLinear().domain([-1, 1]);
            this.yScale = d3.scaleLinear().domain([1, -1]);
            this.xAxis = d3.axisBottom().ticks(10);
            this.yAxis = d3.axisLeft().ticks(10);
            this.svg = d3.select(this.container).append('svg');
            this.plotWrapper = this.svg.append('g');
            this.plotWrapper.attr('transform', `translate(${this.margin.left},${this.margin.top})`);
            this.xAxisLine = this.plotWrapper.append('g').classed('x axis', true);
            this.yAxisLine = this.plotWrapper.append('g').classed('y axis', true);
            this.xAxisTitle = this.xAxisLine.append('text').attr('fill', '#000');
            this.xAxisTitle.style("text-anchor", "middle");
            this.xAxisTitle.append('tspan').text('Y');
            this.xAxisTitle.append('tspan').attr('dy', '3px').text('HEE').attr('font-size', '8px');
            this.xAxisTitle.append('tspan').attr('dy', '-3px').text('   (AU)');
            this.yAxisTitle = this.yAxisLine.append('text').attr('fill', '#000');
            this.yAxisTitle.style("text-anchor", "middle");
            this.yAxisTitle.append('tspan').text('X');
            this.yAxisTitle.append('tspan').attr('dy', '3px').text('HEE').attr('font-size', '8px');
            this.yAxisTitle.append('tspan').attr('dy', '-3px').text('   (AU)');
            this.yAxisTitle.attr('transform', 'rotate(-90)');
            this.sun = this.plotWrapper.append("svg:image").attr('xlink:href', this.options.sun.img).attr('width', '32px').attr('height', '32px');
            this.sun.append('svg:title').text("Sun");
            $(this.svg.node()).hide();
            this.resize();
        }
8d4f8bc2   Goutte   More fixes toward...
1084

4bbc0e4a   Goutte   Continue THE GREA...
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
        initOrbiter(slug, config, data) {
            const thisOrbit = this;
            let orbit_ellipse;
            let orbiter;
            let orbit_line;
            let orbit_section;
            this.data[slug] = data;
            this.orbiters[slug] = config;
            if (data.length) {
                console.info(`Initializing orbit of ${config.name}…`);
            } else {
                console.warn(`No orbit data for ${config.name}…`);
                return;
            }
            if (slug in this.orbitersElements) {
                throw new Error(`Second init of ${slug}.`);
            }
            orbit_ellipse = this.plotWrapper.append("svg:ellipse").classed('orbit orbit_ellipse', true);
            orbiter = this.plotWrapper.append("svg:image").attr('xlink:href', config['img']).attr('width', '32px').attr('height', '32px');
            orbiter.append('svg:title').text(config.name);
            orbit_line = d3.line().x(d => thisOrbit.xScale(d.y)).y(d => thisOrbit.yScale(d.x));
            orbit_section = this.plotWrapper.append('path').datum(data).classed('orbit orbit_section', true);
            this.orbitersElements[slug] = {
                orbiter,
                orbit_ellipse,
                orbit_section,
                orbit_line
            };
            this.orbitersExtrema[slug] = d3.max(data, d => Math.max(Math.abs(d.x), Math.abs(d.y)));
            $(this.svg.node()).show();
            if (config.active) {
                this.enableTarget(slug);
            } else {
                this.disableTarget(slug);
            }
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1122

4bbc0e4a   Goutte   Continue THE GREA...
1123
1124
1125
1126
        enableTarget(slug) {
            this.orbiters[slug].enabled = true;
            return this.showOrbiter(slug);
        }
8d4f8bc2   Goutte   More fixes toward...
1127

4bbc0e4a   Goutte   Continue THE GREA...
1128
1129
1130
1131
        disableTarget(slug) {
            this.orbiters[slug].enabled = false;
            return this.hideOrbiter(slug);
        }
8d4f8bc2   Goutte   More fixes toward...
1132

1185f353   Goutte   Fix the CME Catal...
1133
        showOrbiter(slug, doResize=true) {
4bbc0e4a   Goutte   Continue THE GREA...
1134
1135
            if (!this.data[slug].length) {
                return;
8d4f8bc2   Goutte   More fixes toward...
1136
            }
4bbc0e4a   Goutte   Continue THE GREA...
1137
1138
            if (!this.orbiters[slug].enabled) {
                return;
8d4f8bc2   Goutte   More fixes toward...
1139
            }
4bbc0e4a   Goutte   Continue THE GREA...
1140
1141
1142
1143
            this.orbiters[slug].hidden = false;
            this.orbitersElements[slug].orbiter.style("display", null);
            this.orbitersElements[slug].orbit_ellipse.style("display", null);
            this.orbitersElements[slug].orbit_section.style("display", null);
1185f353   Goutte   Fix the CME Catal...
1144
1145
1146
            if (doResize) this.resize(true);

            return this;
4bbc0e4a   Goutte   Continue THE GREA...
1147
        }
8d4f8bc2   Goutte   More fixes toward...
1148

4bbc0e4a   Goutte   Continue THE GREA...
1149
1150
1151
        hideOrbiter(slug) {
            if (!this.data[slug].length) {
                return;
8d4f8bc2   Goutte   More fixes toward...
1152
            }
4bbc0e4a   Goutte   Continue THE GREA...
1153
1154
1155
1156
1157
1158
            this.orbiters[slug].hidden = true;
            this.orbitersElements[slug].orbiter.style("display", "none");
            this.orbitersElements[slug].orbit_ellipse.style("display", "none");
            this.orbitersElements[slug].orbit_section.style("display", "none");
            return this.resize(true);
        }
8d4f8bc2   Goutte   More fixes toward...
1159

4bbc0e4a   Goutte   Continue THE GREA...
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
        clear() {
            return $(this.svg.node()).remove();
        }

        resize(animate, extremum) {
            let s;
            let o;
            let slug;
            let ref$;
            let config;
            let t;
            let t1;
            animate == null && (animate = false);
            extremum == null && (extremum = null);
            const width = Math.ceil($(this.container).width() - this.margin.left - this.margin.right);
            const height = width; // it's a square
1185f353   Goutte   Fix the CME Catal...
1176
            console.debug(`Resizing orbits : ${width} × ${height}… (animated: ${animate})`);
4bbc0e4a   Goutte   Continue THE GREA...
1177
1178
1179
1180
1181
1182
1183
1184
            if (extremum === null) {
                extremum = 1.1 * d3.max((function () {
                    let ref$;
                    const results$ = [];
                    for (s in ref$ = this.orbiters) {
                        o = ref$[s];
                        if (!o.hidden) {
                            results$.push(this.orbitersExtrema[s]);
8d4f8bc2   Goutte   More fixes toward...
1185
                        }
4bbc0e4a   Goutte   Continue THE GREA...
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
                    }
                    return results$;
                }.call(this)));
            }
            this.xScale = d3.scaleLinear().domain([-1 * extremum, extremum]);
            this.yScale = d3.scaleLinear().domain([extremum, -1 * extremum]);
            this.xScale.range([0, width]);
            this.yScale.range([height, 0]);
            this.svg.attr('width', width + this.margin.right + this.margin.left).attr('height', height + this.margin.top + this.margin.bottom);
            this.sun.attr("x", width / 2.0 - 16).attr("y", height / 2.0 - 16);
            for (slug in ref$ = this.orbiters) {
                config = ref$[slug];
                this.resizeOrbiter(slug, config, width, height, animate);
            }
            this.xAxis.scale(this.xScale);
            this.yAxis.scale(this.yScale);
            this.svg.select('.x.axis').attr('transform', `translate(0,${height})`);
            if (animate) {
                t = this.svg.transition().duration(750);
4bbc0e4a   Goutte   Continue THE GREA...
1205
1206
1207
1208
1209
                this.svg.select('.x.axis').transition(t).call(this.xAxis);
                this.svg.select('.y.axis').transition(t).call(this.yAxis);
            } else {
                this.svg.select('.x.axis').call(this.xAxis);
                this.svg.select('.y.axis').call(this.yAxis);
8d4f8bc2   Goutte   More fixes toward...
1210
            }
60522cb2   Goutte   Clean up a litle.
1211
1212
            this.xAxisTitle.attr("x", width / 2.0).attr("y", 37);
            this.yAxisTitle.attr("x", -1 * height / 2.0).attr("y", -30);
4bbc0e4a   Goutte   Continue THE GREA...
1213
1214
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1215

4bbc0e4a   Goutte   Continue THE GREA...
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
        resizeOrbiter(slug, config, width, height, animate) {
            let data;
            let tt;
            let el;
            let orbit_section;
            let t;
            let a;
            let b;
            let c;
            let cx;
            let cy;
            let orbit_ellipse;
            animate == null && (animate = false);
            data = this.data[slug];
            if (!data.length) {
                return;
            }
            console.debug(`Resizing orbit of ${slug}…`);
            tt = this.svg.transition().duration(750);
            el = this.orbitersElements[slug];
            orbit_section = el['orbit_section'];
            if (animate) {
                t = this.svg.transition().duration(750);
                orbit_section = orbit_section.transition(tt);
            }
            orbit_section.attr('d', el['orbit_line']);
            a = config['orbit']['a'];
            b = config['orbit']['b'];
            c = Math.sqrt(a * a - b * b);
60522cb2   Goutte   Clean up a litle.
1245
1246
            cx = width / 2.0 - c;
            cy = height / 2.0;
4bbc0e4a   Goutte   Continue THE GREA...
1247
1248
1249
1250
1251
1252
1253
1254
1255
            orbit_ellipse = el['orbit_ellipse'];
            if (animate) {
                t = this.svg.transition().duration(750);
                orbit_ellipse = orbit_ellipse.transition(t);
            }
            orbit_ellipse.attr('cx', cx).attr('cy', cy).attr('rx', this.xScale(a) - this.xScale(0)).attr('ry', this.yScale(b) - this.yScale(0));
            this.repositionOrbiter(slug, null, true);
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1256

4bbc0e4a   Goutte   Continue THE GREA...
1257
1258
1259
        zoomToTarget(slug) {
            return this.resize(true, 1.1 * this.orbitersExtrema[slug]);
        }
8d4f8bc2   Goutte   More fixes toward...
1260

4bbc0e4a   Goutte   Continue THE GREA...
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
        repositionOrbiter(slug, datum, animate) {
            let data;
            let el;
            let t;
            animate == null && (animate = false);
            data = this.data[slug];
            if (!data.length) {
                return;
            }
            datum == null && (datum = this.lastOrbiterData[slug]);
            datum == null && (datum = data[data.length - 1]);
            this.lastOrbiterData[slug] = datum;
            el = this.orbitersElements[slug]['orbiter'];
            if (animate) {
                t = this.svg.transition().duration(750);
                el = el.transition(t);
            }
            el.attr('x', this.xScale(datum.y) - 16);
            el.attr('y', this.yScale(datum.x) - 16);
            return this;
        }

        moveToDate(t) {
            let slug;
            let ref$;
            let el;
            let data;
            let i;
            let d0;
            let d1;
            let d;
            if (!t) {
                console.warn("Trying to move to an undefined date !");
            }
            for (slug in ref$ = this.orbitersElements) {
                el = ref$[slug];
8d4f8bc2   Goutte   More fixes toward...
1297
                data = this.data[slug];
4bbc0e4a   Goutte   Continue THE GREA...
1298
1299
1300
1301
1302
                i = this.bisectDate(data, t, 1);
                d0 = data[i - 1];
                d1 = data[i];
                if (!(d1 && d0)) {
                    continue;
8d4f8bc2   Goutte   More fixes toward...
1303
                }
4bbc0e4a   Goutte   Continue THE GREA...
1304
1305
                d = t - d0.t > d1.t - t ? d1 : d0;
                this.repositionOrbiter(slug, d);
8d4f8bc2   Goutte   More fixes toward...
1306
            }
4bbc0e4a   Goutte   Continue THE GREA...
1307
1308
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1309

4bbc0e4a   Goutte   Continue THE GREA...
1310
        resizeDomain(started_at, stopped_at) {
4bbc0e4a   Goutte   Continue THE GREA...
1311
1312
1313
            let config;
            let el;
            let data;
1185f353   Goutte   Fix the CME Catal...
1314
1315
            for (let slug in this.orbiters) {
                config = this.orbiters[slug];
4bbc0e4a   Goutte   Continue THE GREA...
1316
1317
                el = this.orbitersElements[slug];
                data = this.data[slug].filter(onlyDataInRange);
1185f353   Goutte   Fix the CME Catal...
1318
                if ( ! data.length) {
4bbc0e4a   Goutte   Continue THE GREA...
1319
1320
                    this.hideOrbiter(slug);
                    continue;
8d4f8bc2   Goutte   More fixes toward...
1321
                }
4bbc0e4a   Goutte   Continue THE GREA...
1322
1323
                el['orbit_section'].datum(data);
                el['orbit_section'].attr('d', el['orbit_line']);
1185f353   Goutte   Fix the CME Catal...
1324
                this.showOrbiter(slug, false);
8d4f8bc2   Goutte   More fixes toward...
1325
            }
1185f353   Goutte   Fix the CME Catal...
1326
1327
1328
            this.resize(true);

            return this;
8d4f8bc2   Goutte   More fixes toward...
1329

4bbc0e4a   Goutte   Continue THE GREA...
1330
1331
            function onlyDataInRange(d) {
                return started_at <= d.t && d.t <= stopped_at;
8d4f8bc2   Goutte   More fixes toward...
1332
            }
4bbc0e4a   Goutte   Continue THE GREA...
1333
        }
8d4f8bc2   Goutte   More fixes toward...
1334

03452084   Goutte   Make time series'...
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
        // resetZoom() {
        //     let slug;
        //     let ref$;
        //     let config;
        //     let el;
        //     const results$ = [];
        //     for (slug in ref$ = this.orbiters) {
        //         config = ref$[slug];
        //         el = this.orbitersElements[slug];
        //         if (!this.data[slug].length) {
        //             this.hideOrbiter(slug);
        //             continue;
        //         }
        //         el['orbit_section'].datum(this.data[slug]);
        //         el['orbit_section'].attr('d', el['orbit_line']);
        //         results$.push(this.showOrbiter(slug));
        //     }
        //     return results$;
        // }
4bbc0e4a   Goutte   Continue THE GREA...
1354
1355
1356
1357
    }

    Orbits.prototype.bisectDate = d3.bisector(d => d.t).left;

60522cb2   Goutte   Clean up a litle.
1358
1359
    ///////////////////////////////////////////////////////////////////////////

4bbc0e4a   Goutte   Continue THE GREA...
1360
1361
1362
    global.SpaceWeather = SpaceWeather;
    global.TimeSeries = TimeSeries;
    global.Orbits = Orbits;
8d4f8bc2   Goutte   More fixes toward...
1363

5a7474a9   Goutte   Lebab the livescr...
1364
}).call(this);