From 5a7474a9044036e2811e67f3efc8535e04ef528d Mon Sep 17 00:00:00 2001 From: Goutte Date: Thu, 20 Sep 2018 13:11:00 +0200 Subject: [PATCH] Lebab the livescript. --- web/static/js/main.js | 1324 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1324 insertions(+), 0 deletions(-) create mode 100644 web/static/js/main.js diff --git a/web/static/js/main.js b/web/static/js/main.js new file mode 100644 index 0000000..3c73d1b --- /dev/null +++ b/web/static/js/main.js @@ -0,0 +1,1324 @@ +// Generated by LiveScript 1.5.0 +(function(){ + let GOLDEN_RATIO; + let Target; + let SpaceWeather; + let TimeSeries; + let Orbits; + const out$ = typeof exports != 'undefined' && exports || this; + console.debug(out$); + GOLDEN_RATIO = 2 / (1 + Math.sqrt(5)); + Target = ((() => { + // Target.displayName = 'Target'; + // const prototype = Target.prototype; + // const constructor = Target; + function Target(slug, name, config){ + this.slug = slug; + this.name = name; + this.config = config; + this.active = this.config.active; + } + return Target; + })()); + out$.SpaceWeather = SpaceWeather = ((() => { + // "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'; + // let API_TIME_FORMAT; + // let INPUT_TIME_FORMAT; + // const prototype = SpaceWeather.prototype; + // const constructor = SpaceWeather; + const API_TIME_FORMAT = "YYYY-MM-DDTHH:mm:ss"; + const INPUT_TIME_FORMAT = "YYYY-MM-DD"; + + class SpaceWeather { + constructor(configuration) { + let configs; + let res$; + let k; + const this$ = this; + this.configuration = configuration; + console.info("©2017\n _ _ _ _ ____\n | | | | ___| (_) ___ | _ \\ _ __ ___ _ __ __ _\n | |_| |/ _ \\ | |/ _ \\| |_) | '__/ _ \\| '_ \\ / _` |\n | _ | __/ | | (_) | __/| | | (_) | |_) | (_| |\n |_| |_|\\___|_|_|\\___/|_|_ |_|_ \\___/| .__/ \\__,_|\n | |__ _ _ / ___| _ \\| _ \\| _ \\_|\n | '_ \\| | | | | | | | | | |_) | |_) |\n | |_) | |_| | | |___| |_| | __/| __/\n |_.__/ \\__, | \\____|____/|_| |_|\n |___/\n\nThe full source of this website is available at :\nhttps://gitlab.irap.omp.eu/CDPP/SPACEWEATHERONLINE"); + this.targets = {}; + res$ = []; + for (k in this.configuration.targets) { + res$.push(this.configuration.targets[k]); + } + configs = res$; + configs.forEach(target_config => this$.addTarget(new Target(target_config.slug, target_config.name, target_config))); + this.parameters = {}; + this.configuration['parameters'].forEach(p => this$.parameters[p['id']] = p); + this.orbits = null; + this.time_series = []; + } + + init(started_at, stopped_at) { + "This is called by the inline bootstrap javascript code.\nThis ain't in the constructor because it might return a Promise later on.\n(for the loader, for example)"; + const this$ = this; + started_at = moment(started_at).hours(0).minutes(0).seconds(0); + stopped_at = moment(stopped_at).hours(0).minutes(0).seconds(0); + this.setStartAndStop(started_at, stopped_at); + this.loadAndCreatePlots(started_at, stopped_at); + window.addEventListener('resize', () => this$.resize()); + return this; + } + + buildDataUrlForTarget(target_slug, started_at, stopped_at) { + let url; + url = this.configuration['api']['data_for_interval']; + url = url.replace('', target_slug); + url = url.replace('', started_at); + url = url.replace('', stopped_at); + return url; + } + + buildDownloadUrl() { + let ref$; + let started_at; + let stopped_at; + let targets; + let t; + let url; + ref$ = this.getDomain(), started_at = ref$[0], stopped_at = ref$[1]; + targets = (function(){ + const results$ = []; + for (t in this.targets) { + if (this.targets[t].active) { + results$.push(t); + } + } + return results$; + }.call(this)).sort().join('-'); + url = this.configuration['api']['download']; + url = url.replace('', targets); + url = url.replace('', started_at.format(API_TIME_FORMAT)); + url = url.replace('', stopped_at.format(API_TIME_FORMAT)); + return url; + } + + 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); + } + } + 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); + url = url.replace('', parameters); + url = url.replace('', started_at.format(API_TIME_FORMAT)); + url = url.replace('', stopped_at.format(API_TIME_FORMAT)); + return url; + } + + 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$; + let ref$; + 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); + } + } + return results$; + } + + 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(); + } + }); + this.targets[target_slug].active = true; + if ((ref$ = this.orbits) != null) { + ref$.enableTarget(target_slug); + } + return this; + } + + disableTarget(target_slug) { + let ref$; + this.time_series.forEach(ts => { + if (ts.target.slug === target_slug) { + return ts.hide(); + } + }); + this.targets[target_slug].active = false; + if ((ref$ = this.orbits) != null) { + ref$.disableTarget(target_slug); + } + return this; + } + + resize() { + let ref$; + if ((ref$ = this.orbits) != null) { + ref$.resize(); + } + this.time_series.forEach(ts => ts.resize()); + return this; + } + + showLoader() { + return $('#plots_loader').show(); + } + + hideLoader() { + return $('#plots_loader').hide(); + } + + loadData(target_slug, started_at, stopped_at) { + "Load the data as CSV for the specified target and interval,\nand return it in a Promise."; + let sw; + sw = this; + return new Promise((resolve, reject) => { + let url; + url = sw.buildDataUrlForTarget(target_slug, started_at, stopped_at); + return d3.csv(url, csv => { + let timeFormat; + let data; + console.debug(`Requested CSV for ${target_slug}…`, csv); + timeFormat = d3.utcParse('%Y-%m-%dT%H:%M:%S%Z'); + data = { + 'hee': [] + }; + configuration['parameters'].forEach(parameter => data[parameter['id']] = []); + if (!csv) { + reject('invalid'); + } + if (!csv.length) { + reject('empty'); + } + csv.forEach(d => { + let dtime; + dtime = timeFormat(d['time']); + configuration['parameters'].forEach(parameter => { + let id; + let val; + id = parameter['id']; + val = parseFloat(d[id]); + if (!isNaN(val)) { + return data[id].push({ + x: dtime, + y: val + }); + } + }); + if (d['xhee'] && d['yhee']) { + return data['hee'].push({ + t: dtime, + x: parseFloat(d['xhee']), + y: parseFloat(d['yhee']) + }); + } + }); + return resolve(data); + }); + }); + } + + loadAndCreatePlots(started_at, stopped_at) { + "started_at: moment(.js) datetime object\nstopped_at: moment(.js) datetime object"; + 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; + } + 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) { + this$.hideLoader(); + } else { + this$.disableTarget(target.slug); + } + 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; + } + targetButton.addClass('failed'); + targetButton.removeClass('loading'); + this$.hideLoader(); + return handleTarget(i + 1); + }); + }; + handleTarget(0); + return this; + } + + clearPlots() { + this.orbits.clear(); + this.time_series.forEach(ts => ts.clear()); + this.orbits = null; + this.time_series = []; + return this; + } + + createTimeSeries(target, data) { + const this$ = this; + this.configuration['parameters'].forEach(parameter => { + let container; + let id; + let title; + container = this$.configuration['time_series_container']; + 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) { + return this$.time_series.push(new TimeSeries(id, title, target, data[id], this$.parameters[id].active, container, { + 'started_at': this$.started_at, + 'stopped_at': this$.stopped_at + })); + } + }); + this.time_series.forEach(ts => { + ts.options['onMouseOver'] = () => true; + ts.options['onMouseOut'] = () => { + this$.time_series.forEach(ts2 => ts2.hideCursor()); + return true; + }; + ts.options['onMouseMove'] = t => { + let ref$; + this$.time_series.forEach(ts2 => ts2.moveCursor(t)); + if ((ref$ = this$.orbits) != null) { + ref$.moveToDate(t); + } + return true; + }; + ts.options['onBrushEnd'] = (sta, sto) => { + this$.resizeDomain(moment(sta), moment(sto)); + return true; + }; + return ts.options['onDblClick'] = () => { + let ref$; + this$.resetZoom(); + if ((ref$ = $("#zoom_controls_help")) != null) { + ref$.remove(); + } + return true; + }; + }); + return this.time_series; + } + + 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); + } + } + return results$; + } + + enableParameter(parameter_slug) { + const this$ = this; + if (!(parameter_slug in this.parameters)) { + console.error(`Unknown parameter ${parameter_slug}.`); + } + 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(); + } + }); + return this; + } + + disableParameter(parameter_slug) { + if (!(parameter_slug in this.parameters)) { + console.error(`Unknown parameter ${parameter_slug}.`); + } + this.parameters[parameter_slug].active = false; + this.time_series.forEach(ts => { + if (ts.parameter === parameter_slug) { + return ts.hide(); + } + }); + return this; + } + + showCatalogLayer(catalog_slug) { + this.time_series.forEach(ts => ts.showCatalogLayer(catalog_slug)); + return this; + } + + hideCatalogLayer(catalog_slug) { + this.time_series.forEach(ts => ts.hideCatalogLayer(catalog_slug)); + return this; + } + + getDomain() { + if (this.current_started_at != null && this.current_stopped_at != null) { + return [this.current_started_at, this.current_stopped_at]; + } + return [this.started_at, this.stopped_at]; + } + + resizeDomain(started_at, stopped_at) { + let ref$; + let max_stopped_at; + let formatted_started_at; + let formatted_stopped_at; + let tsv; + let tsv_cursor; + let tsv_length; + let zoomedOnVisible; + if (stopped_at < started_at) { + ref$ = [stopped_at, started_at], started_at = ref$[0], stopped_at = ref$[1]; + } + if (started_at === stopped_at) { + console.warn("Please provide distinct start and stop dates."); + return; + } + max_stopped_at = started_at.clone().add(2, 'years'); + if (stopped_at > max_stopped_at) { + console.warn("The time interval was truncated beacuse 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…`); + tsv = this.time_series.filter(ts => ts.visible); + tsv_cursor = 0; + tsv_length = tsv.length; + zoomedOnVisible = new Promise((resolve, reject) => { + let tsv_zoom_on_next; + tsv_zoom_on_next = i => { + let ts; + if (i >= tsv_length) { + resolve(); + return; + } + ts = tsv[i]; + return ts.zoomIn(started_at, stopped_at).then(() => tsv_zoom_on_next(i + 1)); + }; + return tsv_zoom_on_next(0); + }); + zoomedOnVisible.then(function(){ + return this.time_series.forEach(ts => { + if (!ts.visible) { + return ts.zoomIn(started_at, stopped_at); + } + }); + }); + 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); + } + return this; + } + + resetZoom() { + this.time_series.forEach(ts => ts.resetZoom()); + this.orbits.resetZoom(); + this.setStartAndStop(this.started_at, this.stopped_at); + return this; + } + + 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)); + return this; + } + } + + return SpaceWeather; + })()); + + ///////////////////////////////////////////////////////////////////////////// + //// TIME SERIES //////////////////////////////////////////////////////////// + + out$.TimeSeries = TimeSeries = ((() => { + // TimeSeries.displayName = 'TimeSeries'; + const RATIO = GOLDEN_RATIO ** 4; + // const prototype = TimeSeries.prototype; + // const constructor = TimeSeries; + + class TimeSeries { + constructor(parameter, title, target, data, visible, container, options) { + let now; + let res$; + let i$; + let ref$; + let len$; + let d; + this.parameter = parameter; + this.title = title; + this.target = target; + this.data = data; + this.visible = visible; + this.container = container; + this.options = options || {}; + this.onBrushEnd = bind$(this, 'onBrushEnd', this.prototype); + this.onDoubleClick = bind$(this, 'onDoubleClick', this.prototype); + this.onMouseOut = bind$(this, 'onMouseOut', this.prototype); + this.onMouseOver = bind$(this, 'onMouseOver', this.prototype); + this.onMouseMove = bind$(this, 'onMouseMove', this.prototype); + now = moment(); + res$ = []; + for (i$ = 0, len$ = (ref$ = this.data).length; i$ < len$; ++i$) { + d = ref$[i$]; + if (moment(d.x) >= now) { + res$.push(d); + } + } + this.predictiveData = res$; + this.init(); + } + + toString() { + return `${this.title} of ${this.target.name}`; + } + + init() { + let ref$; + let width; + let height; + let formatMillisecond; + let formatSecond; + let formatMinute; + let formatHour; + let formatDay; + let formatWeek; + let formatMonth; + let formatYear; + let multiFormat; + 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 + }; + ref$ = this.recomputeDimensions(), width = ref$[0], height = ref$[1]; + 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']; + } + this.xScale = d3.scaleTime().domain(this.xDataExtent); + this.yScale = d3.scaleLinear().domain(this.yDataExtent); + formatMillisecond = d3.utcFormat(".%L"); + formatSecond = d3.utcFormat(":%S"); + formatMinute = d3.utcFormat("%H:%M"); + formatHour = d3.utcFormat("%H:%M"); + formatDay = d3.utcFormat("%a %d"); + formatWeek = d3.utcFormat("%b %d"); + formatMonth = d3.utcFormat("%B"); + formatYear = d3.utcFormat("%Y"); + multiFormat = date => { + if (date > d3.timeSecond(date)) { + return formatMillisecond(date); + } + if (date > d3.timeMinute(date)) { + return formatSecond(date); + } + if (date > d3.timeHour(date)) { + return formatMinute(date); + } + if (date > d3.timeDay(date)) { + return formatHour(date); + } + if (date > d3.timeMonth(date)) { + if (date > d3.timeWeek(date)) { + return formatDay(date); + } else { + return formatWeek(date); + } + } + if (date > d3.timeYear(date)) { + return formatMonth(date); + } + return formatYear(date); + }; + this.xAxis = d3.axisBottom().tickFormat(multiFormat).ticks(7); + this.yAxis = d3.axisLeft().ticks(10); + this.svg = d3.select(this.container).append('svg'); + this.svg.attr("class", `${this.parameter} ${this.target.slug}`); + this.line = d3.line().x(d => this$.xScale(d.x)).y(d => this$.yScale(d.y)); + this.plotWrapper = this.svg.append('g'); + this.plotWrapper.attr('transform', `translate(${this.margin.left},${this.margin.top})`); + clipId = `ts-clip-${this.parameter}-${this.target.slug}`; + this.clip = this.svg.append("defs").append("svg:clipPath").attr("id", clipId).append("svg:rect").attr("x", 0).attr("y", 0); + this.pathWrapper = this.plotWrapper.append('g'); + this.pathWrapper.attr("clip-path", `url(#${clipId})`); + this.path = this.pathWrapper.append('path').datum(this.data).classed('line', true); + this.predictiveDataPath = this.pathWrapper.append('path').datum(this.predictiveData).classed('predictive-line', true); + this.createCatalogLayers(); + this.horizontalLines = []; + if (this.options['horizontalLines']) { + for (i$ = 0, len$ = (ref$ = this.options['horizontalLines']).length; i$ < len$; ++i$) { + line = ref$[i$]; + 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 + }); + } + } + this.brush = this.plotWrapper.append("g").attr("class", "brush"); + this.plotWrapper.append('g').classed('x axis', true); + this.plotWrapper.append('g').classed('y axis', true); + this.yAxisText = this.plotWrapper.append("text").attr("transform", "rotate(-90)").attr("dy", "1em").style("text-anchor", "middle").text(this.title); + this.yAxisTextTarget = this.plotWrapper.append("text").attr("transform", "rotate(-90)").attr("dy", "1em").style("text-anchor", "middle").style("font-style", "oblique").text(this.target.name); + this.focus = this.plotWrapper.append('g').style("display", "none"); + this.cursorCircle = this.focus.append("circle").attr("class", "cursor-circle").attr("r", 3); + dx = 8; + this.cursorValueShadow = this.focus.append("text").attr("class", "cursor-text cursor-text-shadow").attr("dx", dx).attr("dy", "-.3em"); + this.cursorValue = this.focus.append("text").attr("class", "cursor-text cursor-value").attr("dx", dx).attr("dy", "-.3em"); + this.cursorDateShadow = this.focus.append("text").attr("class", "cursor-text cursor-text-shadow").attr("dx", dx).attr("dy", "1em"); + this.cursorDate = this.focus.append("text").attr("class", "cursor-text cursor-date").attr("dx", dx).attr("dy", "1em"); + this.brushFunction = d3.brushX().extent([[0, 0], [width, height]]).handleSize(0).on("end", this.onBrushEnd); + this.brush.call(this.brushFunction); + this.brushOverlay = this.svg.select(".brush .overlay"); + this.brushOverlay.on("mouseover.swapp", this.onMouseOver).on("mouseout.swapp", this.onMouseOut).on("mousemove.swapp", this.onMouseMove).on("dblclick.swapp", this.onDoubleClick); + return this.resize(); + } + + 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]; + } + + resize() { + let ref$; + let width; + let height; + let i$; + let len$; + let line; + let lineValue; + ref$ = this.recomputeDimensions(), width = ref$[0], height = ref$[1]; + console.debug(`Resizing ${this}: ${width} x ${height}…`); + this.xScale.range([0, width]); + this.yScale.range([height, 0]); + this.svg.attr('width', width + this.margin.right + this.margin.left).attr('height', height + this.margin.top + this.margin.bottom); + this.clip.attr("width", width).attr("height", height); + this.path.attr('d', this.line); + this.predictiveDataPath.attr('d', this.line); + for (i$ = 0, len$ = (ref$ = this.horizontalLines).length; i$ < len$; ++i$) { + line = ref$[i$]; + lineValue = this.yScale(line['config']['value']) + this.margin.top; + line['element'].attr("x1", this.margin.left).attr("y1", lineValue).attr("x2", this.margin.left + width).attr("y2", lineValue); + } + this.xAxis.scale(this.xScale); + this.yAxis.scale(this.yScale); + this.xAxis.ticks(Math.floor(width / 80.0)); + this.yAxis.ticks(Math.floor(height / 18.0)); + this.svg.select('.x.axis').attr('transform', `translate(0,${height})`).call(this.xAxis); + this.svg.select('.y.axis').call(this.yAxis); + this.yAxisText.attr("y", 20 - this.margin.left).attr("x", 0 - height / 2); + this.yAxisTextTarget.attr("y", 0 - this.margin.left).attr("x", 0 - height / 2.0); + this.resizeCatalogLayers(); + if (!this.visible) { + this.hide(); + } + return this; + } + + clear() { + $(this.svg.node()).remove(); + return this.visible = false; + } + + 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); + } + } + + onMouseOver() { + if (this.options.onMouseOver != null) { + return this.options.onMouseOver(); + } else { + return this.showCursor(); + } + } + + onMouseOut() { + if (this.options.onMouseOut != null) { + return this.options.onMouseOut(); + } else { + return this.hideCursor(); + } + } + + onDoubleClick() { + if (this.options.onDblClick != null) { + return this.options.onDblClick(); + } else { + return this.resetZoom(); + } + } + + onBrushEnd() { + let s; + let minmax; + s = d3.event.selection; + if (s) { + minmax = [s[0], s[1]].map(this.xScale.invert, this.xScale); + this.brush.call(this.brushFunction.move, null); + if (this.options.onBrushEnd != null) { + return this.options.onBrushEnd(minmax[0], minmax[1]); + } else { + return this.zoomIn(minmax[0], minmax[1]); + } + } + } + + 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; + } + if (stopDate > maxDate) { + stopDate = maxDate; + } + this.xScale.domain([startDate, stopDate]); + this.yScale.domain(d3.extent(this.data, d => { + let ref$; + if (startDate <= (ref$ = d.x) && ref$ <= stopDate) { + return d.y; + } else { + return 0; + } + })); + return this.applyZoom(); + } + + resetZoom() { + this.xScale.domain(this.xDataExtent); + this.yScale.domain(this.yDataExtent); + return this.applyZoom(); + } + + applyZoom() { + let duration; + let t; + duration = 0; + if (this.visible) { + duration = 750; + console.debug(`Applying zoom to visible ${this}…`); + t = this.svg.transition().duration(duration); + this.svg.select('.x.axis').transition(t).call(this.xAxis); + this.svg.select('.y.axis').transition(t).call(this.yAxis); + this.path.transition(t).attr('d', this.line); + this.predictiveDataPath.transition(t).attr('d', this.line); + } else { + console.debug(`Applying zoom to hidden ${this}…`); + this.svg.select('.x.axis').call(this.xAxis); + this.svg.select('.y.axis').call(this.yAxis); + this.path.attr('d', this.line); + this.predictiveDataPath.attr('d', this.line); + } + this.resizeCatalogLayers(); + this.hideCursor(); + return new Promise((resolve, reject) => { + if (0 === duration) { + return resolve(); + } else { + return setTimeout(() => resolve(), duration + 50); + } + }); + } + + createCatalogLayers() { + let catalog_slug; + let ref$; + let layers; + let i$; + let len$; + let layer; + let started_at; + let stopped_at; + this.layers_rects = {}; + for (catalog_slug in ref$ = this.target.config.layers) { + layers = ref$[catalog_slug]; + this.layers_rects[catalog_slug] = []; + for (i$ = 0, len$ = layers.length; i$ < len$; ++i$) { + layer = layers[i$]; + started_at = moment(layer.start); + stopped_at = moment(layer.stop); + this.layers_rects[catalog_slug].push(this.createCatalogLayer(started_at, stopped_at)); + } + this.hideCatalogLayer(catalog_slug); + } + return this; + } + + createCatalogLayer(started_at, stopped_at) { + let layer_rect; + layer_rect = this.pathWrapper.append("rect").attr('y', 0).attr('height', this.plotHeight).attr('fill', '#FFFD64C2'); + return layer_rect; + } + + resizeCatalogLayers() { + let catalog_slug; + let ref$; + let layers; + let i$; + let len$; + let i; + let layer; + let started_at; + let stopped_at; + let width; + for (catalog_slug in ref$ = this.target.config.layers) { + layers = ref$[catalog_slug]; + for (i$ = 0, len$ = layers.length; i$ < len$; ++i$) { + i = i$; + layer = layers[i$]; + started_at = moment(layer.start); + stopped_at = moment(layer.stop); + width = Math.max(2, this.xScale(stopped_at) - this.xScale(started_at)); + this.layers_rects[catalog_slug][i].attr('x', this.xScale(started_at)).attr('width', width); + } + } + return this; + } + + showCatalogLayer(catalog_slug) { + let i$; + let ref$; + let len$; + let i; + let layer; + for (i$ = 0, len$ = (ref$ = this.target.config.layers[catalog_slug]).length; i$ < len$; ++i$) { + i = i$; + layer = ref$[i$]; + this.layers_rects[catalog_slug][i].style("display", null); + } + return this; + } + + hideCatalogLayer(catalog_slug) { + let i$; + let ref$; + let len$; + let i; + let layer; + for (i$ = 0, len$ = (ref$ = this.target.config.layers[catalog_slug]).length; i$ < len$; ++i$) { + i = i$; + layer = ref$[i$]; + this.layers_rects[catalog_slug][i].style("display", "none"); + } + return this; + } + + showCursor() { + return this.focus.style("display", null); + } + + hideCursor() { + return this.focus.style("display", "none"); + } + + moveCursor(x0) { + let i; + let d0; + let d1; + let d; + let xx; + let yy; + let mirrored; + let dx; + let transform; + i = this.bisectDate(this.data, x0, 1); + d0 = this.data[i - 1]; + d1 = this.data[i]; + if (!d1 || !d0) { + this.hideCursor(); + return; + } + d = x0 - d0.x > d1.x - x0 ? d1 : d0; + xx = this.xScale(d.x); + yy = this.yScale(d.y); + mirrored = this.plotWidth != null && xx > this.plotWidth / 2; + dx = 8; + if (mirrored) { + dx = -1 * dx; + } + transform = `translate(${xx}, ${yy})`; + this.cursorCircle.attr("transform", transform); + this.cursorValue.attr("transform", transform).text(d.y).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx); + this.cursorValueShadow.attr("transform", transform).text(d.y).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx); + this.cursorDate.attr("transform", transform).text(this.timeFormat(d.x)).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx); + this.cursorDateShadow.attr("transform", transform).text(this.timeFormat(d.x)).attr('text-anchor', mirrored ? 'end' : 'start').attr("dx", dx); + this.showCursor(); + return this; + } + } + + TimeSeries.prototype.bisectDate = d3.bisector(d => d.x).left; + TimeSeries.prototype.timeFormat = d3.utcFormat("%Y-%m-%d %H:%M"); + return TimeSeries; + })()); + out$.Orbits = Orbits = ((() => { + // "View of the solar system from above, with orbits segments for selected time\ninterval, from real data."; + // Orbits.displayName = 'Orbits'; + // const prototype = Orbits.prototype; + // const constructor = Orbits; + + class Orbits { + constructor(container, options) { + this.container = container; + this.options = options != null + ? 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(); + } + + initOrbiter(slug, config, data) { + let orbit_ellipse; + let orbiter; + let orbit_line; + let orbit_section; + const this$ = this; + 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 => this$.xScale(d.y)).y(d => this$.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; + } + + enableTarget(slug) { + this.orbiters[slug].enabled = true; + return this.showOrbiter(slug); + } + + disableTarget(slug) { + this.orbiters[slug].enabled = false; + return this.hideOrbiter(slug); + } + + showOrbiter(slug) { + if (!this.data[slug].length) { + return; + } + if (!this.orbiters[slug].enabled) { + return; + } + 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); + return this.resize(true); + } + + hideOrbiter(slug) { + if (!this.data[slug].length) { + return; + } + 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); + } + + clear() { + return $(this.svg.node()).remove(); + } + + resize(animate, extremum) { + let width; + let height; + let s; + let o; + let slug; + let ref$; + let config; + let t; + let t1; + animate == null && (animate = false); + extremum == null && (extremum = null); + width = Math.ceil($(this.container).width() - this.margin.left - this.margin.right); + height = Math.ceil(1.0 * width); + console.debug(`Resizing orbits : ${width} × ${height}…`); + 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]); + } + } + 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); + t1 = this.svg.transition().duration(4750); + 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); + } + this.xAxisTitle.attr("x", width / 2).attr("y", 37); + this.yAxisTitle.attr("x", -1 * height / 2).attr("y", -30); + return this; + } + + 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); + cx = width / 2 - c; + cy = height / 2; + 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; + } + + zoomToTarget(slug) { + return this.resize(true, 1.1 * this.orbitersExtrema[slug]); + } + + 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]; + data = this.data[slug]; + i = this.bisectDate(data, t, 1); + d0 = data[i - 1]; + d1 = data[i]; + if (!(d1 && d0)) { + continue; + } + d = t - d0.t > d1.t - t ? d1 : d0; + this.repositionOrbiter(slug, d); + } + return this; + } + + resizeDomain(started_at, stopped_at) { + let slug; + let ref$; + let config; + let el; + let data; + const results$ = []; + for (slug in ref$ = this.orbiters) { + config = ref$[slug]; + el = this.orbitersElements[slug]; + data = this.data[slug].filter(onlyDataInRange); + if (!data.length) { + this.hideOrbiter(slug); + continue; + } + el['orbit_section'].datum(data); + el['orbit_section'].attr('d', el['orbit_line']); + results$.push(this.showOrbiter(slug)); + } + return results$; + function onlyDataInRange(d){ + return started_at <= d.t && d.t <= stopped_at; + } + } + + 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$; + } + } + + Orbits.prototype.bisectDate = d3.bisector(d => d.t).left; + return Orbits; + })()); + function bind$(obj, key, target){ + return function(){ return (target || obj)[key].apply(obj, arguments) }; + } +}).call(this); -- libgit2 0.21.2