Blame view

web/static/js/main.js 72 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
            this.configuration['parameters'].forEach(p => that.parameters[p['id']] = p);
            this.orbits = null;
            this.time_series = [];
11d86851   Goutte   Add support for s...
86
87
88
89
90
91
92

            // Holds the downloaded data for each layer hash
            // layer hash => data (array of dict)
            this._image_preview_layers_data = {};
            // Holds the activation status for each layer hash
            // layer hash => activation status (bool)
            this._image_preview_layers_live = {};
4bbc0e4a   Goutte   Continue THE GREA...
93
        }
8d4f8bc2   Goutte   More fixes toward...
94

56d84302   Goutte   Continue the grea...
95
96
97
98
99
100
101
102
        /**
         * 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...
103
        init(started_at, stopped_at) {
1185f353   Goutte   Fix the CME Catal...
104
            const app = this;
56d84302   Goutte   Continue the grea...
105
106
107

            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...
108
109
            this.setStartAndStop(started_at, stopped_at);
            this.loadAndCreatePlots(started_at, stopped_at);
1185f353   Goutte   Fix the CME Catal...
110
            window.addEventListener('resize', () => app.resize());
56d84302   Goutte   Continue the grea...
111

4bbc0e4a   Goutte   Continue THE GREA...
112
113
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
114

4bbc0e4a   Goutte   Continue THE GREA...
115
116
117
118
119
120
        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...
121

4bbc0e4a   Goutte   Continue THE GREA...
122
123
            return url;
        }
8d4f8bc2   Goutte   More fixes toward...
124

4bbc0e4a   Goutte   Continue THE GREA...
125
126
127
128
        buildDownloadUrl() {
            let ref$;
            let started_at;
            let stopped_at;
4bbc0e4a   Goutte   Continue THE GREA...
129
130
131
            let t;
            let url;
            ref$ = this.getDomain(), started_at = ref$[0], stopped_at = ref$[1];
1ab47144   Goutte   Add new menus, up...
132
            const targets = (function () {
8d4f8bc2   Goutte   More fixes toward...
133
                const results$ = [];
4bbc0e4a   Goutte   Continue THE GREA...
134
135
136
                for (t in this.targets) {
                    if (this.targets[t].active) {
                        results$.push(t);
8d4f8bc2   Goutte   More fixes toward...
137
138
139
                    }
                }
                return results$;
4bbc0e4a   Goutte   Continue THE GREA...
140
            }.call(this)).sort().join('-');
1ab47144   Goutte   Add new menus, up...
141
            // const targets = this.getEnabledTargetsNames().sort().join('-');
4bbc0e4a   Goutte   Continue THE GREA...
142
143
144
145
            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));
1ab47144   Goutte   Add new menus, up...
146
            console.log(targets);
4bbc0e4a   Goutte   Continue THE GREA...
147
148
            return url;
        }
8d4f8bc2   Goutte   More fixes toward...
149

4bbc0e4a   Goutte   Continue THE GREA...
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        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...
165
                    }
8d4f8bc2   Goutte   More fixes toward...
166
                }
4bbc0e4a   Goutte   Continue THE GREA...
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
                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...
185

4bbc0e4a   Goutte   Continue THE GREA...
186
187
188
189
190
191
192
193
194
        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...
195
                let ref$;
4bbc0e4a   Goutte   Continue THE GREA...
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
                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...
221
                }
8d4f8bc2   Goutte   More fixes toward...
222
            }
4bbc0e4a   Goutte   Continue THE GREA...
223
224
            return results$;
        }
5a7474a9   Goutte   Lebab the livescr...
225

4bbc0e4a   Goutte   Continue THE GREA...
226
227
228
229
230
231
        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...
232
                }
4bbc0e4a   Goutte   Continue THE GREA...
233
234
            });
            this.targets[target_slug].active = true;
79d621c7   hitier   Dont draw orbit f...
235
236
237
            if( this.targets[target_slug].config.type == 'input'){
                return this;
            }
4bbc0e4a   Goutte   Continue THE GREA...
238
239
            if ((ref$ = this.orbits) != null) {
                ref$.enableTarget(target_slug);
8d4f8bc2   Goutte   More fixes toward...
240
            }
4bbc0e4a   Goutte   Continue THE GREA...
241
242
            return this;
        }
5a7474a9   Goutte   Lebab the livescr...
243

4bbc0e4a   Goutte   Continue THE GREA...
244
245
246
247
248
249
250
251
        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;
79d621c7   hitier   Dont draw orbit f...
252
253
254
            if( this.targets[target_slug].config.type == 'input'){
                return this;
            }
4bbc0e4a   Goutte   Continue THE GREA...
255
256
            if ((ref$ = this.orbits) != null) {
                ref$.disableTarget(target_slug);
8d4f8bc2   Goutte   More fixes toward...
257
            }
4bbc0e4a   Goutte   Continue THE GREA...
258
259
            return this;
        }
5a7474a9   Goutte   Lebab the livescr...
260

4bbc0e4a   Goutte   Continue THE GREA...
261
        resize() {
1185f353   Goutte   Fix the CME Catal...
262
263
            if (null != this.orbits) {
                this.orbits.resize();
8d4f8bc2   Goutte   More fixes toward...
264
            }
4bbc0e4a   Goutte   Continue THE GREA...
265
266
267
            this.time_series.forEach(ts => ts.resize());
            return this;
        }
5a7474a9   Goutte   Lebab the livescr...
268

4bbc0e4a   Goutte   Continue THE GREA...
269
270
271
272
273
274
275
276
        showLoader() {
            return $('#plots_loader').show();
        }

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

326b749d   Goutte   Finally, a decent...
277
278
279
280
281
282
283
284
285
        /**
         * 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...
286
        loadData(target_slug, started_at, stopped_at) {
326b749d   Goutte   Finally, a decent...
287
            let app = this;
4bbc0e4a   Goutte   Continue THE GREA...
288
            return new Promise((resolve, reject) => {
326b749d   Goutte   Finally, a decent...
289
                let url = app.buildDataUrlForTarget(target_slug, started_at, stopped_at);
4bbc0e4a   Goutte   Continue THE GREA...
290
291
292
293
294
295
296
297
                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': []
                    };
11d86851   Goutte   Add support for s...
298
                    app.configuration['parameters'].forEach(parameter => data[parameter['id']] = []);
4bbc0e4a   Goutte   Continue THE GREA...
299
300
301
302
303
304
305
306
307
                    if (!csv) {
                        reject('invalid');
                    }
                    if (!csv.length) {
                        reject('empty');
                    }
                    csv.forEach(d => {
                        let dtime;
                        dtime = timeFormat(d['time']);
11d86851   Goutte   Add support for s...
308
                        app.configuration['parameters'].forEach(parameter => {
4bbc0e4a   Goutte   Continue THE GREA...
309
310
311
312
313
314
315
316
                            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...
317
318
319
                                });
                            }
                        });
4bbc0e4a   Goutte   Continue THE GREA...
320
321
322
323
324
325
326
                        if (d['xhee'] && d['yhee']) {
                            return data['hee'].push({
                                t: dtime,
                                x: parseFloat(d['xhee']),
                                y: parseFloat(d['yhee'])
                            });
                        }
8d4f8bc2   Goutte   More fixes toward...
327
                    });
4bbc0e4a   Goutte   Continue THE GREA...
328
                    return resolve(data);
8d4f8bc2   Goutte   More fixes toward...
329
                });
4bbc0e4a   Goutte   Continue THE GREA...
330
331
            });
        }
8d4f8bc2   Goutte   More fixes toward...
332

56d84302   Goutte   Continue the grea...
333
334
335
336
337
338
        /**
         *
         * @param started_at moment(.js) datetime object
         * @param stopped_at moment(.js) datetime object
         * @returns {SpaceWeather}
         */
4bbc0e4a   Goutte   Continue THE GREA...
339
        loadAndCreatePlots(started_at, stopped_at) {
4bbc0e4a   Goutte   Continue THE GREA...
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
            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...
367
                }
4bbc0e4a   Goutte   Continue THE GREA...
368
369
370
371
372
373
374
375
376
                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...
377
                        this$.hideLoader();
4bbc0e4a   Goutte   Continue THE GREA...
378
379
                    } else {
                        this$.disableTarget(target.slug);
8d4f8bc2   Goutte   More fixes toward...
380
                    }
4bbc0e4a   Goutte   Continue THE GREA...
381
382
383
384
385
386
387
388
389
390
391
392
393
                    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...
394
                    }
866991ff   Goutte   Add Jupiter's CME...
395
                    target.active = false;
4bbc0e4a   Goutte   Continue THE GREA...
396
397
398
399
                    targetButton.addClass('failed');
                    targetButton.removeClass('loading');
                    this$.hideLoader();
                    return handleTarget(i + 1);
8d4f8bc2   Goutte   More fixes toward...
400
                });
4bbc0e4a   Goutte   Continue THE GREA...
401
402
403
404
            };
            handleTarget(0);
            return this;
        }
db69e5a7   Goutte   Continue implemen...
405

4bbc0e4a   Goutte   Continue THE GREA...
406
407
408
409
410
411
412
        clearPlots() {
            this.orbits.clear();
            this.time_series.forEach(ts => ts.clear());
            this.orbits = null;
            this.time_series = [];
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
413

4bbc0e4a   Goutte   Continue THE GREA...
414
        createTimeSeries(target, data) {
03452084   Goutte   Make time series'...
415
            const app = this;
4bbc0e4a   Goutte   Continue THE GREA...
416
417
418
419
            this.configuration['parameters'].forEach(parameter => {
                let container;
                let id;
                let title;
03452084   Goutte   Make time series'...
420
                container = app.configuration['time_series_container'];
4bbc0e4a   Goutte   Continue THE GREA...
421
422
423
424
425
426
427
                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) {
fd4c583f   hitier   Add source name t...
428
429
                    //console.log('-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+')
                    console.log(id, title, target, data[id], container)
03452084   Goutte   Make time series'...
430
431
432
                    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...
433
                    }));
8d4f8bc2   Goutte   More fixes toward...
434
                }
4bbc0e4a   Goutte   Continue THE GREA...
435
            });
03452084   Goutte   Make time series'...
436
            this.time_series.forEach((ts, tsk) => {
4bbc0e4a   Goutte   Continue THE GREA...
437
438
                ts.options['onMouseOver'] = () => true;
                ts.options['onMouseOut'] = () => {
03452084   Goutte   Make time series'...
439
                    app.time_series.forEach(ts2 => ts2.hideCursor());
4bbc0e4a   Goutte   Continue THE GREA...
440
441
                    return true;
                };
11d86851   Goutte   Add support for s...
442
443
444
445
446
447
                ts.options['onMouseMove'] = time => {
                    app.time_series.forEach(ts2 =>
                        ts2.moveCursor(time)
                    );
                    if (app.orbits != null) {
                        app.orbits.moveToDate(time);
8d4f8bc2   Goutte   More fixes toward...
448
                    }
11d86851   Goutte   Add support for s...
449
450
                    ts.updateImagePreviewFromCursor(time);

4bbc0e4a   Goutte   Continue THE GREA...
451
452
                    return true;
                };
03452084   Goutte   Make time series'...
453
454
455
456

                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...
457
                    return true;
03452084   Goutte   Make time series'...
458
459
                }).bind(ts);

1185f353   Goutte   Fix the CME Catal...
460
                ts.options['onDblClick'] = () => {
26733e9f   Goutte   Make the animatio...
461
462
463
464
                    app.resetZoom(ts);
                    let zoom_controls_help = $("#zoom_controls_help");
                    if (zoom_controls_help) {
                        zoom_controls_help.remove();
4bbc0e4a   Goutte   Continue THE GREA...
465
466
467
468
469
470
                    }
                    return true;
                };
            });
            return this.time_series;
        }
db69e5a7   Goutte   Continue implemen...
471

4bbc0e4a   Goutte   Continue THE GREA...
472
473
474
475
476
477
478
479
480
481
482
483
484
        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...
485
486
            }

4bbc0e4a   Goutte   Continue THE GREA...
487
488
            return results$;
        }
db69e5a7   Goutte   Continue implemen...
489

4bbc0e4a   Goutte   Continue THE GREA...
490
491
492
493
        enableParameter(parameter_slug) {
            const this$ = this;
            if (!(parameter_slug in this.parameters)) {
                console.error(`Unknown parameter ${parameter_slug}.`);
8d4f8bc2   Goutte   More fixes toward...
494
            }
4bbc0e4a   Goutte   Continue THE GREA...
495
496
497
498
499
500
            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...
501

4bbc0e4a   Goutte   Continue THE GREA...
502
503
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
504

4bbc0e4a   Goutte   Continue THE GREA...
505
506
507
        disableParameter(parameter_slug) {
            if (!(parameter_slug in this.parameters)) {
                console.error(`Unknown parameter ${parameter_slug}.`);
8d4f8bc2   Goutte   More fixes toward...
508
            }
4bbc0e4a   Goutte   Continue THE GREA...
509
510
511
512
            this.parameters[parameter_slug].active = false;
            this.time_series.forEach(ts => {
                if (ts.parameter === parameter_slug) {
                    return ts.hide();
8d4f8bc2   Goutte   More fixes toward...
513
                }
4bbc0e4a   Goutte   Continue THE GREA...
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
            });

            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;
        }

11d86851   Goutte   Add support for s...
529
530
531
532
533
534
535
536
537
538
539
540
541
        ///////////////////////////////////////////////////////////////////////

        hashImagePreviewLayer(target_slug, layer_slug) {
            return target_slug + "_" + layer_slug;
        }

        getImagePreviewData(target_slug, layer_slug) {
            const app = this; // not taking any risks with `this` binding.
            return new Promise((resolve, reject) => {
                const h = app.hashImagePreviewLayer(target_slug, layer_slug);
                if (h in this._image_preview_layers_data) {
                    resolve(app._image_preview_layers_data[h]);
                } else {
866991ff   Goutte   Add Jupiter's CME...
542
                    let url_route = target_slug + "_auroral_catalog.csv";
11d86851   Goutte   Add support for s...
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
                    let url = app.configuration['api']['root'] + url_route;
                    //url += "/" + url_route; // Extra / yields havoc -- flask?
                    let d3csv = d3.csv(url, csv => {
                        console.info("Fetched image preview CSV data.", url, csv);
                        console.assert(app === this); // peace of mind
                        // Now's a good time to do some pre-process on the data
                        let data = csv.map(d => {
                            return {
                                time_min: moment(d.time_min),
                                time_max: moment(d.time_max),
                                thumbnail_url: d.thumbnail_url.trim(),
                                external_link: d.external_link.trim()
                            };
                        });
                        app._image_preview_layers_data[h] = data;
                        // … also a good place to build an index for example,
                        // since right now we're bisecting on each cursor move,
                        // and that's expensive. (Binary Search)
                        resolve(data);
                    });
                }
            });
        }

        isImagePreviewLayerShown(target_slug, layer_slug) {
            const h = this.hashImagePreviewLayer(target_slug, layer_slug);
            if (h in this._image_preview_layers_live) {
                return this._image_preview_layers_live[h];
            } else {
                return false;
            }
        }

        showImagePreviewLayer(target_slug, layer_slug) {
            const app = this;

            return new Promise((resolve, reject) => {
                if (this.isImagePreviewLayerShown(target_slug, layer_slug)) {
                    resolve(); // already shown
                }
                const h = this.hashImagePreviewLayer(target_slug, layer_slug);
                //console.log("showImagePreviewLayer", h);
                //console.log("_image_preview_layers_data", this._image_preview_layers_data);

                this._image_preview_layers_live[h] = true;

                const data_promise = this.getImagePreviewData(target_slug, layer_slug);
                data_promise.then((data) => {
                    //console.debug("getImagePreviewData OK !", data);
                    let ts_left_to_process = this.time_series.length;
                    this.time_series.forEach(ts => {
                        if (ts.target.slug === target_slug) {
81960a4f   Goutte   Fix an issue repo...
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
                            ts.showImagePreviewLayer(layer_slug, data)
                                .then(
                                    () => {
                                        //ts_left_to_process--;
                                        //console.debug("showImagePreviewLayer promise ok!");
                                    },
                                    (err) => {
                                        //ts_left_to_process--;
                                        //console.error("showImagePreviewLayer promise failed.", err);
                                    }
                                )
                                .finally(() => {
                                    ts_left_to_process--;
                                    if (0 === ts_left_to_process) {
                                        //console.debug("showImagePreviewLayer resolve");
                                        resolve();
                                    }
                                });
11d86851   Goutte   Add support for s...
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
                        } else {
                            ts_left_to_process--;
                        }
                    });
                }, (err) => {
                    console.error("getImagePreviewData promise failed.", err);
                    reject(err);
                });

            });
        }

        hideImagePreviewLayer(target_slug, layer_slug) {
            // perhaps make this promise-based as well?

            if ( ! this.isImagePreviewLayerShown(target_slug, layer_slug)) {
                return; // already hidden
            }

            const h = this.hashImagePreviewLayer(target_slug, layer_slug);
11d86851   Goutte   Add support for s...
633
634
635
636
637
638
639
640
641
642
643

            this._image_preview_layers_live[h] = false;

            let ts;
            for (let key in this.time_series) {
                if ( ! this.time_series.hasOwnProperty(key)) continue;
                ts = this.time_series[key];
                if (ts.target.slug !== target_slug) continue;
                ts.hideImagePreviewLayer(layer_slug);
            }

81960a4f   Goutte   Fix an issue repo...
644
645
646
647
648
649
            this.hideImagePreview();
        }

        hideImagePreview() {
            const box = jQuery('#time_series_cursor_morebox'); // sorry
            box.addClass('hidden');
11d86851   Goutte   Add support for s...
650
651
        }

4bbc0e4a   Goutte   Continue THE GREA...
652
653
654
        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...
655
            }
4bbc0e4a   Goutte   Continue THE GREA...
656
657
            return [this.started_at, this.stopped_at];
        }
8d4f8bc2   Goutte   More fixes toward...
658

03452084   Goutte   Make time series'...
659
        resizeDomain(started_at, stopped_at, starting_ts) {
4bbc0e4a   Goutte   Continue THE GREA...
660
661
662
            let max_stopped_at;
            let formatted_started_at;
            let formatted_stopped_at;
4bbc0e4a   Goutte   Continue THE GREA...
663
            if (stopped_at < started_at) {
326b749d   Goutte   Finally, a decent...
664
665
666
                let tmp_at = started_at;
                started_at = stopped_at;
                stopped_at = tmp_at;
4bbc0e4a   Goutte   Continue THE GREA...
667
668
            }
            if (started_at === stopped_at) {
326b749d   Goutte   Finally, a decent...
669
                alert("Please provide distinct start and stop dates.");
4bbc0e4a   Goutte   Continue THE GREA...
670
671
672
673
674
675
676
677
678
679
680
681
682
                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'...
683
684
685
686
                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;
26733e9f   Goutte   Make the animatio...
687
688
689
                const zoomedOnVisible = new Promise((resolve, reject) => {
                    console.log("Zoom on visible time series…");
                    const tsv_zoom_on_next = i => {
4bbc0e4a   Goutte   Continue THE GREA...
690
691
692
693
                        if (i >= tsv_length) {
                            resolve();
                            return;
                        }
26733e9f   Goutte   Make the animatio...
694
                        let ts = tsv[(Math.ceil(i/2)*(i%2>0?1:-1)+starting_ts_key+tsv_length)%tsv_length];
4bbc0e4a   Goutte   Continue THE GREA...
695
696
697
                        ts.zoomIn(started_at, stopped_at)
                          .then(() => tsv_zoom_on_next(i + 1));
                    };
1185f353   Goutte   Fix the CME Catal...
698
                    tsv_zoom_on_next(0);
4bbc0e4a   Goutte   Continue THE GREA...
699
700
                });
                zoomedOnVisible.then(() => {
1185f353   Goutte   Fix the CME Catal...
701
                    console.log("Now zoom on invisible time series…");
4bbc0e4a   Goutte   Continue THE GREA...
702
703
704
705
                    this.time_series.forEach(ts => {
                        if (!ts.visible) {
                            ts.zoomIn(started_at, stopped_at);
                        }
8d4f8bc2   Goutte   More fixes toward...
706
                    });
4bbc0e4a   Goutte   Continue THE GREA...
707
708
709
710
711
712
713
                });
                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...
714
            }
4bbc0e4a   Goutte   Continue THE GREA...
715
716
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
717

26733e9f   Goutte   Make the animatio...
718
719
        resetZoom(starting_ts) {
            this.resizeDomain(this.started_at, this.stopped_at, starting_ts);
4bbc0e4a   Goutte   Continue THE GREA...
720
721
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
722

4bbc0e4a   Goutte   Continue THE GREA...
723
724
725
726
727
728
        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...
729

4bbc0e4a   Goutte   Continue THE GREA...
730
            return this;
5a7474a9   Goutte   Lebab the livescr...
731
        }
4bbc0e4a   Goutte   Continue THE GREA...
732
    }
5a7474a9   Goutte   Lebab the livescr...
733

8d4f8bc2   Goutte   More fixes toward...
734
735
736
737

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

4bbc0e4a   Goutte   Continue THE GREA...
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
    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...
760
                }
8d4f8bc2   Goutte   More fixes toward...
761
            }
4bbc0e4a   Goutte   Continue THE GREA...
762
            this.predictiveData = predictiveData;
11d86851   Goutte   Add support for s...
763
764
765
766
767
768
769
770
771
772
773
774
775
776

            this._image_preview_layers_live = {}; // layer_hash => is active? (bool)
            this._image_preview_layers_rect = {}; // layer_hash => rects (array)
            this._image_preview_layers_data = {}; // layer_hash => data (array) (/!. not a copy)
            // datum example:
            // {
            //   time_min: moment("2017-09-09 00:13:49.845227"),
            //   thumbnail_url: "http://voparis-srv.obspm.fr/vo/planeto/apis/dataset/Bastet/Saturn_-_2017_14_Feb-09_Sept/od9u21u4q_proc_small.jpg",
            //   time_max: moment("2017-09-09 00:58:50.044784"),
            //   external_link: "http://apis.obspm.fr/spip.php?page=observation&id=bas_8167"
            // }
            // Note that time_min and time_max are pre-processed
            // to moment.js instances already during creation.

4bbc0e4a   Goutte   Continue THE GREA...
777
778
            this.init();
        }
8d4f8bc2   Goutte   More fixes toward...
779

4bbc0e4a   Goutte   Continue THE GREA...
780
781
782
        toString() {
            return `${this.title} of ${this.target.name}`;
        }
8d4f8bc2   Goutte   More fixes toward...
783

4bbc0e4a   Goutte   Continue THE GREA...
784
        init() {
4bbc0e4a   Goutte   Continue THE GREA...
785
786
787
788
789
790
791
792
793
794
795
796
797
798
            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...
799
800
801
            let dimensions = this.recomputeDimensions();
            let width  = dimensions[0];
            let height = dimensions[1];
4bbc0e4a   Goutte   Continue THE GREA...
802
803
804
805
806
807
808
809
            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...
810
            this.xScale = d3.scaleUtc().domain(this.xDataExtent);
4bbc0e4a   Goutte   Continue THE GREA...
811
            this.yScale = d3.scaleLinear().domain(this.yDataExtent);
326b749d   Goutte   Finally, a decent...
812
813

            // http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html
56d84302   Goutte   Continue the grea...
814
815
816
817
818
819
820
821
            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...
822
            const formatDoy = d3.utcFormat("%Y-%j");
922540d4   hitier   Change date axis ...
823
            const formatDate= d3.utcFormat("%Y-%m-%d");
56d84302   Goutte   Continue the grea...
824
            const multiFormat = date => {
326b749d   Goutte   Finally, a decent...
825
                if (date > d3.utcSecond(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
826
                    return formatMillisecond(date);
8d4f8bc2   Goutte   More fixes toward...
827
                }
326b749d   Goutte   Finally, a decent...
828
                if (date > d3.utcMinute(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
829
                    return formatSecond(date);
8d4f8bc2   Goutte   More fixes toward...
830
                }
326b749d   Goutte   Finally, a decent...
831
                if (date > d3.utcHour(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
832
833
                    return formatMinute(date);
                }
326b749d   Goutte   Finally, a decent...
834
                if (date > d3.utcDay(date)) {
4bbc0e4a   Goutte   Continue THE GREA...
835
836
                    return formatHour(date);
                }
56d84302   Goutte   Continue the grea...
837

922540d4   hitier   Change date axis ...
838
                return formatDate(date);
326b749d   Goutte   Finally, a decent...
839
840
841
842
843
844
845
846
847
848
849
850
                // 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...
851
            };
326b749d   Goutte   Finally, a decent...
852

1750ad5f   hitier   Fix date axis number
853
            this.xAxis = d3.axisBottom().tickFormat(multiFormat);//.ticks(7);
4bbc0e4a   Goutte   Continue THE GREA...
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
            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...
869
870
                for (i$ = 0, len$ = (dimensions = this.options['horizontalLines']).length; i$ < len$; ++i$) {
                    line = dimensions[i$];
4bbc0e4a   Goutte   Continue THE GREA...
871
872
873
874
875
                    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...
876
                }
8d4f8bc2   Goutte   More fixes toward...
877
            }
4bbc0e4a   Goutte   Continue THE GREA...
878
879
880
881
            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);
7f4cbd1d   hitier   Set ytitle for ta...
882
883
884
885
886
887
            let y_title = ''
            if ( this.target.config.type == 'input'){
                y_title = this.target.name;
            } else {
                y_title = this.target.name+" from "+$("input[name='input_slug']:checked").siblings(".mdl-radio__label").html();
            }
fd4c583f   hitier   Add source name t...
888
889
890
            this.yAxisTextTarget = this.plotWrapper.append("text").attr("transform", "rotate(-90)")
                                        .attr("dy", "1em").style("text-anchor", "middle")
                                        .style("font-style", "oblique").text(y_title);
4bbc0e4a   Goutte   Continue THE GREA...
891
892
893
894
895
896
897
898
899
900
901
902
903
            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...
904

4bbc0e4a   Goutte   Continue THE GREA...
905
906
907
908
909
910
911
912
913
        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...
914

4bbc0e4a   Goutte   Continue THE GREA...
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
        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);
1750ad5f   hitier   Fix date axis number
938
939
//            this.xAxis.ticks(Math.floor(width / 80.0));
            this.xAxis.ticks(10)
4bbc0e4a   Goutte   Continue THE GREA...
940
941
942
943
944
945
            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();
11d86851   Goutte   Add support for s...
946
            this.resizeImagePreviewLayers();
4bbc0e4a   Goutte   Continue THE GREA...
947
948
949
950
951
952
953
954
955
956
            if (!this.visible) {
                this.hide();
            }
            return this;
        }

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

4bbc0e4a   Goutte   Continue THE GREA...
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
        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...
975
            }
4bbc0e4a   Goutte   Continue THE GREA...
976
        }
8d4f8bc2   Goutte   More fixes toward...
977

4bbc0e4a   Goutte   Continue THE GREA...
978
979
980
981
982
        onMouseOver() {
            if (this.options.onMouseOver != null) {
                return this.options.onMouseOver();
            } else {
                return this.showCursor();
8d4f8bc2   Goutte   More fixes toward...
983
            }
4bbc0e4a   Goutte   Continue THE GREA...
984
        }
8d4f8bc2   Goutte   More fixes toward...
985

4bbc0e4a   Goutte   Continue THE GREA...
986
987
988
989
990
        onMouseOut() {
            if (this.options.onMouseOut != null) {
                return this.options.onMouseOut();
            } else {
                return this.hideCursor();
8d4f8bc2   Goutte   More fixes toward...
991
            }
4bbc0e4a   Goutte   Continue THE GREA...
992
        }
8d4f8bc2   Goutte   More fixes toward...
993

4bbc0e4a   Goutte   Continue THE GREA...
994
995
996
997
998
        onDoubleClick() {
            if (this.options.onDblClick != null) {
                return this.options.onDblClick();
            } else {
                return this.resetZoom();
8d4f8bc2   Goutte   More fixes toward...
999
            }
4bbc0e4a   Goutte   Continue THE GREA...
1000
        }
8d4f8bc2   Goutte   More fixes toward...
1001

4bbc0e4a   Goutte   Continue THE GREA...
1002
        onBrushEnd() {
03452084   Goutte   Make time series'...
1003
            let s = d3.event.selection;
4bbc0e4a   Goutte   Continue THE GREA...
1004
            if (s) {
03452084   Goutte   Make time series'...
1005
                let minmax = [s[0], s[1]].map(this.xScale.invert, this.xScale);
4bbc0e4a   Goutte   Continue THE GREA...
1006
1007
                this.brush.call(this.brushFunction.move, null);
                if (this.options.onBrushEnd != null) {
03452084   Goutte   Make time series'...
1008
1009
                    // same, the 'this' is still the old one
                    // return this.options.onBrushEnd.apply(this, [minmax[0], minmax[1]]);
4bbc0e4a   Goutte   Continue THE GREA...
1010
                    return this.options.onBrushEnd(minmax[0], minmax[1]);
8d4f8bc2   Goutte   More fixes toward...
1011
                } else {
4bbc0e4a   Goutte   Continue THE GREA...
1012
                    return this.zoomIn(minmax[0], minmax[1]);
8d4f8bc2   Goutte   More fixes toward...
1013
1014
                }
            }
4bbc0e4a   Goutte   Continue THE GREA...
1015
        }
8d4f8bc2   Goutte   More fixes toward...
1016

4bbc0e4a   Goutte   Continue THE GREA...
1017
1018
1019
1020
1021
1022
1023
1024
        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...
1025
            }
4bbc0e4a   Goutte   Continue THE GREA...
1026
1027
1028
1029
1030
            if (stopDate > maxDate) {
                stopDate = maxDate;
            }
            this.xScale.domain([startDate, stopDate]);
            this.yScale.domain(d3.extent(this.data, d => {
8d4f8bc2   Goutte   More fixes toward...
1031
                let ref$;
4bbc0e4a   Goutte   Continue THE GREA...
1032
1033
1034
1035
                if (startDate <= (ref$ = d.x) && ref$ <= stopDate) {
                    return d.y;
                } else {
                    return 0;
8d4f8bc2   Goutte   More fixes toward...
1036
                }
4bbc0e4a   Goutte   Continue THE GREA...
1037
1038
1039
            }));
            return this.applyZoom();
        }
8d4f8bc2   Goutte   More fixes toward...
1040

4bbc0e4a   Goutte   Continue THE GREA...
1041
        applyZoom() {
1185f353   Goutte   Fix the CME Catal...
1042
            let duration = 0;
4bbc0e4a   Goutte   Continue THE GREA...
1043
1044
1045
1046
            duration = 0;
            if (this.visible) {
                duration = 750;
                console.debug(`Applying zoom to visible ${this}…`);
1185f353   Goutte   Fix the CME Catal...
1047
                let t = this.svg.transition().duration(duration);
4bbc0e4a   Goutte   Continue THE GREA...
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
                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();
11d86851   Goutte   Add support for s...
1060
            this.resizeImagePreviewLayers();
4bbc0e4a   Goutte   Continue THE GREA...
1061
1062
1063
1064
            this.hideCursor();
            return new Promise((resolve, reject) => {
                if (0 === duration) {
                    return resolve();
8d4f8bc2   Goutte   More fixes toward...
1065
                } else {
4bbc0e4a   Goutte   Continue THE GREA...
1066
                    return setTimeout(() => resolve(), duration + 50);
8d4f8bc2   Goutte   More fixes toward...
1067
                }
4bbc0e4a   Goutte   Continue THE GREA...
1068
1069
            });
        }
8d4f8bc2   Goutte   More fixes toward...
1070

11d86851   Goutte   Add support for s...
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
        createLayerRect(started_at, stopped_at, color) {
            // We're ignoring the parameters, since we're
            // doing the resize logic in resizeXXX()
            let layer_rect; // positioning is done in resize()
            layer_rect = this.pathWrapper.append("rect")
                .attr('y', 0)
                .attr('height', this.plotHeight) // => move to resize too?
                .attr('fill', color);
            //won't work, possibly because of our input catcher rect.
            //layer_rect.append('svg:title').text("!");
            return layer_rect;
        }

4bbc0e4a   Goutte   Continue THE GREA...
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
        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) {
11d86851   Goutte   Add support for s...
1095
                if ( ! (ref$.hasOwnProperty(catalog_slug))) continue; // oh, js
4bbc0e4a   Goutte   Continue THE GREA...
1096
1097
1098
1099
1100
1101
                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);
11d86851   Goutte   Add support for s...
1102
                    this.layers_rects[catalog_slug].push(this.createCatalogLayerRect(started_at, stopped_at));
8d4f8bc2   Goutte   More fixes toward...
1103
                }
4bbc0e4a   Goutte   Continue THE GREA...
1104
                this.hideCatalogLayer(catalog_slug);
8d4f8bc2   Goutte   More fixes toward...
1105
            }
4bbc0e4a   Goutte   Continue THE GREA...
1106
1107
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1108

11d86851   Goutte   Add support for s...
1109
1110
        createCatalogLayerRect(started_at, stopped_at) {
            return this.createLayerRect(started_at, stopped_at, '#FFFD64C2');
4bbc0e4a   Goutte   Continue THE GREA...
1111
        }
8d4f8bc2   Goutte   More fixes toward...
1112

4bbc0e4a   Goutte   Continue THE GREA...
1113
        resizeCatalogLayers() {
11d86851   Goutte   Add support for s...
1114
1115
1116
1117
            let animate = true; // move to param if needed
            // Perhaps make that transition part of the prototype instead?
            let t = this.svg.transition().duration(750);

4bbc0e4a   Goutte   Continue THE GREA...
1118
1119
1120
            let catalog_slug;
            let ref$;
            let layers;
4bbc0e4a   Goutte   Continue THE GREA...
1121
1122
1123
1124
1125
1126
1127
            let len$;
            let i;
            let layer;
            let started_at;
            let stopped_at;
            let width;
            for (catalog_slug in ref$ = this.target.config.layers) {
11d86851   Goutte   Add support for s...
1128
                if ( ! (ref$.hasOwnProperty(catalog_slug))) continue;
4bbc0e4a   Goutte   Continue THE GREA...
1129
                layers = ref$[catalog_slug];
11d86851   Goutte   Add support for s...
1130
1131
                for (i = 0, len$ = layers.length; i < len$; ++i) {
                    layer = layers[i];
4bbc0e4a   Goutte   Continue THE GREA...
1132
1133
1134
                    started_at = moment(layer.start);
                    stopped_at = moment(layer.stop);
                    width = Math.max(2, this.xScale(stopped_at) - this.xScale(started_at));
11d86851   Goutte   Add support for s...
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146

                    if (animate) {
                        this.layers_rects[catalog_slug][i]
                            .transition(t)
                            .attr('x', this.xScale(started_at))
                            .attr('width', width);
                    } else {
                        this.layers_rects[catalog_slug][i]
                            .attr('x', this.xScale(started_at))
                            .attr('width', width);
                    }

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

4bbc0e4a   Goutte   Continue THE GREA...
1152
        showCatalogLayer(catalog_slug) {
4bbc0e4a   Goutte   Continue THE GREA...
1153
1154
1155
1156
            let ref$;
            let len$;
            let i;
            let layer;
11d86851   Goutte   Add support for s...
1157
1158
            for (i = 0, len$ = (ref$ = this.target.config.layers[catalog_slug]).length; i < len$; ++i) {
                layer = ref$[i];
4bbc0e4a   Goutte   Continue THE GREA...
1159
1160
1161
1162
                this.layers_rects[catalog_slug][i].style("display", null);
            }
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1163

4bbc0e4a   Goutte   Continue THE GREA...
1164
        hideCatalogLayer(catalog_slug) {
4bbc0e4a   Goutte   Continue THE GREA...
1165
1166
1167
            let ref$;
            let len$;
            let i;
11d86851   Goutte   Add support for s...
1168
1169
1170
            //let layer;
            for (i = 0, len$ = (ref$ = this.target.config.layers[catalog_slug]).length; i < len$; ++i) {
                //layer = ref$[i];
4bbc0e4a   Goutte   Continue THE GREA...
1171
1172
1173
1174
                this.layers_rects[catalog_slug][i].style("display", "none");
            }
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1175

11d86851   Goutte   Add support for s...
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
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
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
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
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
        ///////////////////////////////////////////////////////////////////////

        hasImagePreviewLayer(layer_slug) {
            return layer_slug in this._image_preview_layers_data;
        }

        // createImagePreviewLayers(layer_slug, data) {
        //
        // }

        createImagePreviewLayer(layer_slug, data) {
            this._image_preview_layers_data[layer_slug] = data;
            this._image_preview_layers_rect[layer_slug] = [];
            this._image_preview_layers_live[layer_slug] = true;
            let datum;
            for (let key in data) {
                if (data.hasOwnProperty(key)) {
                    if ("columns" === key) continue;
                    // console.debug("datum", key, data[key]);
                    datum = data[key];
                    // { time_min: "2017-09-09 00:13:49.845227", thumbnail_url: "http://voparis-srv.obspm.fr/vo/planeto/apis/dataset/Bastet/Saturn_-_2017_14_Feb-09_Sept/od9u21u4q_proc_small.jpg", time_max: "2017-09-09 00:58:50.044784", external_link: "http://apis.obspm.fr/spip.php?page=observation&id=bas_8167" }
                    this._image_preview_layers_rect[layer_slug].push(
                        this.createImagePreviewLayerRect(
                            datum.time_min, datum.time_max
                        )
                    );
                }
            }
        }

        isImagePreviewLayerLive(layer_slug) {
            if (layer_slug in this._image_preview_layers_live) {
                return this._image_preview_layers_live[layer_slug];
            } else {
                return false;
            }
        }

        resizeImagePreviewLayers() {
            for (let layer_slug in this._image_preview_layers_live) {
                if (!(this._image_preview_layers_live.hasOwnProperty(layer_slug)))
                    continue;
                console.debug("Resize image layer", layer_slug);
                this.resizeImagePreviewLayer(layer_slug);
            }
        }

        resizeImagePreviewLayer(layer_slug) {
            if (! this.isImagePreviewLayerLive(layer_slug)) {
                return;
            }

            const rects = this._image_preview_layers_rect[layer_slug];
            if (! rects) {
                console.error(
                    "Tried to resize an image preview layer without rects.",
                    layer_slug, this
                );
                return;
            }

            const data = this._image_preview_layers_data[layer_slug];
            if (! data) {
                console.error(
                    "Tried to resize an image preview layer without data.",
                    layer_slug, this
                );
                return;
            }

            let animate = true;
            let t = this.svg.transition().duration(750);

            let width;
            let started_at;
            let stopped_at;
            //for (let [dkey, datum] of data) { // nope
            let datum;
            for (let dkey in data) {
                if ( ! data.hasOwnProperty(dkey)) continue;
                if ("columns" === dkey) continue;

                datum = data[dkey];

                // We assume that moment(moment(x)) == moment(x) (it's true)
                // Remove these moment() casts for some more perfs since we're
                // already casting to moment() in the data pre-process.
                started_at = moment(datum.time_min);
                stopped_at = moment(datum.time_max);

                //console.debug("Resize image layer rect", started_at, stopped_at);

                width = this.xScale(stopped_at) - this.xScale(started_at);
                // Under 2 pixels wide the rects appear glitchy
                width = Math.max(2, width);

                if (animate) {
                    rects[dkey]
                        .transition(t)
                        .attr('x', this.xScale(started_at))
                        .attr('width', width);
                } else {
                    rects[dkey]
                        .attr('x', this.xScale(started_at))
                        .attr('width', width);
                }

            }
        }

        static get COLOR_IMAGE_PREVIEW_LAYER() {
            return '#FF339942';
        }

        static get COLOR_IMAGE_PREVIEW_LAYER_ACTIVE() {
            return '#FF3399D2';
        }

        createImagePreviewLayerRect(started_at, stopped_at) {
            return this.createLayerRect(
                started_at, stopped_at, TimeSeries.COLOR_IMAGE_PREVIEW_LAYER
            );
        }

        highlightImagePreviewLayerRect(layer_slug, rect_key) {
            const rects = this._image_preview_layers_rect[layer_slug];
            if (! rects) {
                console.error(
                    "Tried to highlight an image preview layer without rects.",
                    layer_slug, this
                );
                return;
            }

            const rect_to_highlight = rects[rect_key];
            if (! rect_to_highlight) {
                console.error(
                    "Tried to highlight a non-existent rect.",
                    layer_slug, rect_key, this
                );
                return;
            }

            for (let rect of rects) {
                TimeSeries.setRectColor(
                    rect, TimeSeries.COLOR_IMAGE_PREVIEW_LAYER
                );
            }
            TimeSeries.setRectColor(
                rect_to_highlight, TimeSeries.COLOR_IMAGE_PREVIEW_LAYER_ACTIVE
            );

        }

        static setRectColor(rect, color) {
            rect.attr('fill', color);
        }

        showImagePreviewLayer(layer_slug, data) {
            return new Promise((resolve, reject) => {
                //console.log("showImagePreviewLayer Promise…");

                if (this._image_preview_layers_live[layer_slug]) {
                    console.warn("TS.showImagePreviewLayer: already shown.");
                    resolve(); // we're already shown
                }

                if ( ! this.hasImagePreviewLayer(layer_slug)) {
                    this.createImagePreviewLayer(layer_slug, data);
                }

                this._image_preview_layers_live[layer_slug] = true;

                this.resizeImagePreviewLayer(layer_slug);

                const rects = this._image_preview_layers_rect[layer_slug];
                if (! rects) {
                    console.error(
                        "Tried to show an image preview layer without rects.",
                        layer_slug, this
                    );
                    return;
                }

                for (let rect of rects) {
                    rect.style("display", null)
                }

                resolve();
            });
        }

        hideImagePreviewLayer(layer_slug) {
            // console.log(
            //     "TS.hideImagePreviewLayer()",
            //     this._image_preview_layers_live[layer_slug],
            //     this._image_preview_layers_live
            // );
            if ( ! this._image_preview_layers_live[layer_slug]) {
                console.warn("TS.hideImagePreviewLayer: already hidden.");
                return; // we're already hidden
            }
            this._image_preview_layers_live[layer_slug] = false;

            const rects = this._image_preview_layers_rect[layer_slug];
            //console.debug("RECTS", rects);

            if (! rects) {
                console.error(
                    "Tried to hide an image preview layer without rects.",
                    layer_slug, this
                );
                return;
            }


            for (let rect of rects) {
                rect.style("display", "none");
            }
        }

        showImagePreview(image_url, external_link, comment) {
            const box = jQuery('#time_series_cursor_morebox');
            const img = jQuery('#time_series_cursor_image');
            const cil = jQuery('#time_series_cursor_image_link');
            const cic = jQuery('#time_series_cursor_image_comment');
            const lnk = jQuery('#time_series_cursor_link');

            const previous_image_url = img.attr('src');
            if (image_url === previous_image_url) {
                return;
            }

            img.attr('src', image_url);
            lnk.attr('href', external_link);
            cic.html(comment);

            // Interesting ; using the regex in the prototype yields … fails
            // Race conditions are probably reunited, afaik.
            //const match = this.imageRegex.exec(image_url);
            // Let's compile our regex every time instead. Optimize later.
            const imageRegex = /(.+?)_small([.][a-zA-Z0-9]+)$/g;
            const match = imageRegex.exec(image_url);
            let image_link = "#";
            if (match) {
                //console.log("Matched image url!", match, image_url);
                image_link = match[1] + match[2]; // remove the `_small`
            } else {
                console.warn("Could not find bigger image for url:", image_url);
            }
            cil.attr('href', image_link);

            box.removeClass('hidden');
        }

81960a4f   Goutte   Fix an issue repo...
1431
1432
1433
1434
        hideImagePreview() {
            const box = jQuery('#time_series_cursor_morebox');
            box.addClass('hidden');
        }
11d86851   Goutte   Add support for s...
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476

        updateImagePreviewFromCursor(x0) {
            let data = this._image_preview_layers_data;
            let i;
            let layer_slug;
            for (layer_slug in data) {
                if ( ! data.hasOwnProperty(layer_slug))
                    continue;
                if ( ! this.isImagePreviewLayerLive(layer_slug)) {
                    continue;
                }
                i = this.bisectIpod(data[layer_slug], x0, 1);
                //console.debug("Found i ", i, x0, data[layer_slug]);
                if (i == null) continue; // ignore errors and data out of range
                break;
            }
            if (i == null) {
                //console.debug("No live image preview found.");
                return;
            }

            let d0 = data[layer_slug][i - 1];
            let d1 = data[layer_slug][i];
            if (!d1 || !d0) {
                //this.hideImagePreview();
                return;
            }
            let d = x0 - d0.time_min > d1.time_min - x0 ? d1 : d0;

            //console.info("Cursor", x0, d0);

            this.highlightImagePreviewLayerRect(
                layer_slug, d === d0 ? i-1 : i
            );
            this.showImagePreview(
                d.thumbnail_url, d.external_link,
                "Integration: "+d.time_min.from(d.time_max, true)
            );
        }

        ///////////////////////////////////////////////////////////////////////

4bbc0e4a   Goutte   Continue THE GREA...
1477
1478
1479
        showCursor() {
            return this.focus.style("display", null);
        }
8d4f8bc2   Goutte   More fixes toward...
1480

4bbc0e4a   Goutte   Continue THE GREA...
1481
1482
1483
1484
1485
        hideCursor() {
            return this.focus.style("display", "none");
        }

        moveCursor(x0) {
11d86851   Goutte   Add support for s...
1486
1487
1488
            let i = this.bisectDate(this.data, x0, 1);
            let d0 = this.data[i - 1];
            let d1 = this.data[i];
4bbc0e4a   Goutte   Continue THE GREA...
1489
1490
1491
1492
            if (!d1 || !d0) {
                this.hideCursor();
                return;
            }
11d86851   Goutte   Add support for s...
1493
1494
1495
            let d = x0 - d0.x > d1.x - x0 ? d1 : d0;
            let xx = this.xScale(d.x);
            let yy = this.yScale(d.y);
4bbc0e4a   Goutte   Continue THE GREA...
1496
            const mirrored = this.plotWidth != null && xx > this.plotWidth / 2;
11d86851   Goutte   Add support for s...
1497
            let dx = 8;
4bbc0e4a   Goutte   Continue THE GREA...
1498
1499
1500
            if (mirrored) {
                dx = -1 * dx;
            }
11d86851   Goutte   Add support for s...
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
            const transform = `translate(${xx}, ${yy})`;
            this.cursorCircle
                .attr("transform", transform);
            this.cursorValue
                .text(d.y)
                .attr("transform", transform)
                .attr('text-anchor', mirrored ? 'end' : 'start')
                .attr("dx", dx);
            this.cursorValueShadow
                .text(d.y)
                .attr("transform", transform)
                .attr('text-anchor', mirrored ? 'end' : 'start')
                .attr("dx", dx);
            this.cursorDate
                .text(this.timeFormat(d.x))
                .attr("transform", transform)
                .attr('text-anchor', mirrored ? 'end' : 'start')
                .attr("dx", dx);
            this.cursorDateShadow
                .text(this.timeFormat(d.x))
                .attr("transform", transform)
                .attr('text-anchor', mirrored ? 'end' : 'start')
                .attr("dx", dx);
4bbc0e4a   Goutte   Continue THE GREA...
1524
            this.showCursor();
11d86851   Goutte   Add support for s...
1525

4bbc0e4a   Goutte   Continue THE GREA...
1526
            return this;
5a7474a9   Goutte   Lebab the livescr...
1527
        }
4bbc0e4a   Goutte   Continue THE GREA...
1528
    }
8d4f8bc2   Goutte   More fixes toward...
1529

11d86851   Goutte   Add support for s...
1530
1531
1532
    // Don't use the prototype for a regex ; there are race conditions
    //TimeSeries.prototype.imageRegex = /(.+?)_small([.][a-zA-Z0-9]+)$/g;
    TimeSeries.prototype.bisectIpod = d3.bisector(d => d.time_min).left;
4bbc0e4a   Goutte   Continue THE GREA...
1533
1534
    TimeSeries.prototype.bisectDate = d3.bisector(d => d.x).left;
    TimeSeries.prototype.timeFormat = d3.utcFormat("%Y-%m-%d %H:%M");
db69e5a7   Goutte   Continue implemen...
1535
1536
1537
1538
1539


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

4bbc0e4a   Goutte   Continue THE GREA...
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
    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...
1581

4bbc0e4a   Goutte   Continue THE GREA...
1582
        initOrbiter(slug, config, data) {
4bbc0e4a   Goutte   Continue THE GREA...
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
            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...
1619

4bbc0e4a   Goutte   Continue THE GREA...
1620
1621
1622
1623
        enableTarget(slug) {
            this.orbiters[slug].enabled = true;
            return this.showOrbiter(slug);
        }
8d4f8bc2   Goutte   More fixes toward...
1624

4bbc0e4a   Goutte   Continue THE GREA...
1625
1626
1627
1628
        disableTarget(slug) {
            this.orbiters[slug].enabled = false;
            return this.hideOrbiter(slug);
        }
8d4f8bc2   Goutte   More fixes toward...
1629

1185f353   Goutte   Fix the CME Catal...
1630
        showOrbiter(slug, doResize=true) {
4bbc0e4a   Goutte   Continue THE GREA...
1631
1632
            if (!this.data[slug].length) {
                return;
8d4f8bc2   Goutte   More fixes toward...
1633
            }
4bbc0e4a   Goutte   Continue THE GREA...
1634
1635
            if (!this.orbiters[slug].enabled) {
                return;
8d4f8bc2   Goutte   More fixes toward...
1636
            }
4bbc0e4a   Goutte   Continue THE GREA...
1637
1638
1639
1640
            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...
1641
1642
1643
            if (doResize) this.resize(true);

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

4bbc0e4a   Goutte   Continue THE GREA...
1646
1647
1648
        hideOrbiter(slug) {
            if (!this.data[slug].length) {
                return;
8d4f8bc2   Goutte   More fixes toward...
1649
            }
4bbc0e4a   Goutte   Continue THE GREA...
1650
1651
1652
1653
1654
1655
            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...
1656

4bbc0e4a   Goutte   Continue THE GREA...
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
        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...
1673
            console.debug(`Resizing orbits : ${width} × ${height}… (animated: ${animate})`);
4bbc0e4a   Goutte   Continue THE GREA...
1674
1675
1676
1677
1678
1679
1680
1681
            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...
1682
                        }
4bbc0e4a   Goutte   Continue THE GREA...
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
                    }
                    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...
1702
1703
1704
1705
1706
                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...
1707
            }
60522cb2   Goutte   Clean up a litle.
1708
1709
            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...
1710
1711
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1712

4bbc0e4a   Goutte   Continue THE GREA...
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
        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.
1742
1743
            cx = width / 2.0 - c;
            cy = height / 2.0;
4bbc0e4a   Goutte   Continue THE GREA...
1744
1745
1746
1747
1748
1749
1750
1751
1752
            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...
1753

4bbc0e4a   Goutte   Continue THE GREA...
1754
1755
1756
        zoomToTarget(slug) {
            return this.resize(true, 1.1 * this.orbitersExtrema[slug]);
        }
8d4f8bc2   Goutte   More fixes toward...
1757

4bbc0e4a   Goutte   Continue THE GREA...
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
        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...
1794
                data = this.data[slug];
4bbc0e4a   Goutte   Continue THE GREA...
1795
1796
1797
1798
1799
                i = this.bisectDate(data, t, 1);
                d0 = data[i - 1];
                d1 = data[i];
                if (!(d1 && d0)) {
                    continue;
8d4f8bc2   Goutte   More fixes toward...
1800
                }
4bbc0e4a   Goutte   Continue THE GREA...
1801
1802
                d = t - d0.t > d1.t - t ? d1 : d0;
                this.repositionOrbiter(slug, d);
8d4f8bc2   Goutte   More fixes toward...
1803
            }
4bbc0e4a   Goutte   Continue THE GREA...
1804
1805
            return this;
        }
8d4f8bc2   Goutte   More fixes toward...
1806

4bbc0e4a   Goutte   Continue THE GREA...
1807
        resizeDomain(started_at, stopped_at) {
4bbc0e4a   Goutte   Continue THE GREA...
1808
1809
1810
            let config;
            let el;
            let data;
1185f353   Goutte   Fix the CME Catal...
1811
1812
            for (let slug in this.orbiters) {
                config = this.orbiters[slug];
4bbc0e4a   Goutte   Continue THE GREA...
1813
1814
                el = this.orbitersElements[slug];
                data = this.data[slug].filter(onlyDataInRange);
1185f353   Goutte   Fix the CME Catal...
1815
                if ( ! data.length) {
4bbc0e4a   Goutte   Continue THE GREA...
1816
1817
                    this.hideOrbiter(slug);
                    continue;
8d4f8bc2   Goutte   More fixes toward...
1818
                }
4bbc0e4a   Goutte   Continue THE GREA...
1819
1820
                el['orbit_section'].datum(data);
                el['orbit_section'].attr('d', el['orbit_line']);
1185f353   Goutte   Fix the CME Catal...
1821
                this.showOrbiter(slug, false);
8d4f8bc2   Goutte   More fixes toward...
1822
            }
1185f353   Goutte   Fix the CME Catal...
1823
1824
1825
            this.resize(true);

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

4bbc0e4a   Goutte   Continue THE GREA...
1827
1828
            function onlyDataInRange(d) {
                return started_at <= d.t && d.t <= stopped_at;
8d4f8bc2   Goutte   More fixes toward...
1829
            }
4bbc0e4a   Goutte   Continue THE GREA...
1830
        }
8d4f8bc2   Goutte   More fixes toward...
1831

03452084   Goutte   Make time series'...
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
        // 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...
1851
1852
1853
1854
    }

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

60522cb2   Goutte   Clean up a litle.
1855
1856
    ///////////////////////////////////////////////////////////////////////////

4bbc0e4a   Goutte   Continue THE GREA...
1857
1858
1859
    global.SpaceWeather = SpaceWeather;
    global.TimeSeries = TimeSeries;
    global.Orbits = Orbits;
8d4f8bc2   Goutte   More fixes toward...
1860

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