Interactive interface for browsing global, full-resolution satellite imagery
Add proj util tests -- redux
Benjamin King9e8d453bfe9e
diff --git a/web/js/fixtures.js b/web/js/fixtures.jsindex 2300b9b65..ad53783c0 100644--- a/web/js/fixtures.js+++ b/web/js/fixtures.js@@ -1,12 +1,12 @@import proj4 from 'proj4';import { register } from 'ol/proj/proj4';-import { dateModel } from './date/model';-import { layersModel } from './layers/model';-import { mapModel } from './map/model';-import { palettesModel } from './palettes/model';-import { projectionModel } from './projection/model';-import { compareModel } from './compare/model';+// import { dateModel } from './date/model';+// import { layersModel } from './layers/model';+// import { mapModel } from './map/model';+// import { palettesModel } from './palettes/model';+// import { projectionModel } from './projection/model';+// import { compareModel } from './compare/model';var fixtures = {red: 'ff0000ff',@@ -158,21 +158,27 @@ fixtures.config = function() {};};-fixtures.models = function(config) {- var models = {};+// fixtures.models = function(config) {+// var models = {};- models.proj = projectionModel(config);- models.layers = layersModel(models, config);- models.palettes = palettesModel(models, config);- models.map = mapModel(models, config);- models.compare = compareModel(models, config);- models.date = dateModel(models, config);- return models;-};+// models.proj = projectionModel(config);+// models.layers = layersModel(models, config);+// models.palettes = palettesModel(models, config);+// models.map = mapModel(models, config);+// models.compare = compareModel(models, config);+// models.date = dateModel(models, config);+// return models;+// };export function registerProjections() {- proj4.defs('EPSG:3413', '+title=WGS 84 / NSIDC Sea Ice Polar Stereographic North +proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs');- proj4.defs('EPSG:3031', '+title=WGS 84 / Antarctic Polar Stereographic +proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs');+ proj4.defs(+ 'EPSG:3413',+ '+title=WGS 84 / NSIDC Sea Ice Polar Stereographic North +proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'+ );+ proj4.defs(+ 'EPSG:3031',+ '+title=WGS 84 / Antarctic Polar Stereographic +proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'+ );register(proj4);}diff --git a/web/js/map/animation/anim.js b/web/js/map/animation/anim.jsdeleted file mode 100644index 5ec8a479e..000000000--- a/web/js/map/animation/anim.js+++ /dev/null@@ -1,30 +0,0 @@-import lodashEach from 'lodash/each';--export function parse(state, errors) {- if (state.a) {- var str = state.a;- var astate = {- attributes: []- };-- // Get text before (- var on = str.match(/[^(,]+/)[0];- if (on !== 'on') {- // don't do anything if wrong format- state.ab = undefined;- return;- }-- // remove (, get key value pairs- str = str.match(/\(.*\)/)[0].replace(/[()]/g, '');- var kvps = str.split(',');- lodashEach(kvps, function(kvp) {- var parts = kvp.split('=');- astate.attributes.push({- id: parts[0],- value: parts[1]- });- });- state.a = astate;- }-}diff --git a/web/js/map/animation/gif-stream.js b/web/js/map/animation/gif-stream.jsdeleted file mode 100644index 70f9ba485..000000000--- a/web/js/map/animation/gif-stream.js+++ /dev/null@@ -1,224 +0,0 @@-import GifWriter from 'gifwriter';-import NeuQuant from 'neuquant';-import Promise from 'bluebird';-import { ReadableStream } from 'web-streams-polyfill';-import lodashEach from 'lodash/each';--export default class GifStream {- constructor() {- this.canvas = null;- this.ctx = null;- }- /**- * Add frame contents to canvas- *- * https://github.com/yahoo/gifshot/blob/master/src/modules/core/AnimatedGIF.js- *- * @param {Object} ctx 2d Canvas Context- * @param {Object} img Image Element- * @param {String} frameText Text to be applied to this string- *- * @return {Object} 2d Canvas Context- */- addFrameDetails(ctx, img) {- const options = this.options;- const frameText = img.text;- const {- fontColor,- fontSize,- fontFamily,- fontWeight,- gifHeight,- gifWidth,- text,- textAlign,- textBaseline,- waterMark,- waterMarkHeight,- waterMarkWidth,- waterMarkXCoordinate,- waterMarkYCoordinate- } = options;- const textXCoordinate = options.textXCoordinate ? options.textXCoordinate : textAlign === 'left' ? 1 : textAlign === 'right' ? gifWidth : gifWidth / 2;- const textYCoordinate = options.textYCoordinate ? options.textYCoordinate : textBaseline === 'top' ? 1 : textBaseline === 'center' ? gifHeight / 2 : gifHeight;- const font = fontWeight + ' ' + fontSize + ' ' + fontFamily;- const textToUse = (frameText && options.showFrameText) ? frameText : text;-- try {- ctx.drawImage(img, 0, 0, gifWidth, gifHeight);- if (textToUse) {- ctx.font = font;- ctx.fillStyle = fontColor;- ctx.textAlign = textAlign;- ctx.textBaseline = textBaseline;- if (options.stroke) {- const stroke = options.stroke;- ctx.strokeStyle = stroke.color;- ctx.lineWidth = stroke.pixels * 2;- ctx.strokeText(frameText, textXCoordinate, textYCoordinate);- }- ctx.fillText(textToUse, textXCoordinate, textYCoordinate);- }- if (waterMark) {- ctx.drawImage(waterMark, waterMarkXCoordinate, waterMarkYCoordinate, waterMarkWidth, waterMarkHeight);- }- return ctx;- } catch (e) {- return '' + e;- }- }- /**- * Create GIF from options- *- * @param {Object} options GIF options- * @param {Function} callback Function to call once GIF is created- * @return {void}- */- createGIF(options, callback) {- if (this.canvas) this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);- this.canvas = document.createElement('canvas');- this.ctx = this.canvas.getContext('2d');- this.options = options;- this.canvas.width = options.gifWidth;- this.canvas.height = options.gifHeight;-- var imagePromiseArray = [];- lodashEach(options.images, (imageObj) => {- imagePromiseArray.push(this.getImagePromise(imageObj).catch(returnError));- });- function returnError(e) {- const callbackObj = {- blob: null,- error: e- };- callback(callbackObj);- }- Promise.all(imagePromiseArray).then((images) => {- var gifStream = this.getStream(images, this.ctx);- var reader = gifStream.getReader();- var chunks = [];- var processedImages = 1;- function finished(chunks) {- const callbackObj = {- blob: new Blob(chunks, { type: 'image/gif' }),- error: ''- };- callback(callbackObj);- };-- function pull() {- const imageLength = options.images.length;- return reader.read().then(function (result) {- const chunk = result.value;- if (result.done) {- finished(chunks);- } else {- chunks.push(new Uint8Array(chunk));- options.progressCallback(Math.round((processedImages / imageLength) * 100));- processedImages++;- setTimeout(function() { // This was needed in order for callback to be applied- return pull();- }, 10);- }- });- };- options.progressCallback(0);- pull();- });- }- getImagePromise(frame) {- return new Promise((resolve, reject) => {- var img = new Image();- img.width = this.options.gifWidth;- img.height = this.options.gifHeight;- img.text = frame.text;- img.delay = frame.delay;- img.crossOrigin = 'Anonymous';- img.onload = () => {- URL.revokeObjectURL(img.src); // Free up some memory- resolve(img);- delete img.onload;- delete img.onerror;- };- img.onerror = (e) => {- reject(e);- delete img.onload;- delete img.onerror;- };- img.src = frame.src;- });- }- /**- * Generate GIF-creating Stream- * @param {Array} frames Array of GIF image objects- * @param {Object} ctx 2d Canvas Cntext- * @return {Object} Returns GifWriter Stream- */- getStream(frames, ctx) {- var options = this.options;- var width = options.gifWidth;- var height = options.gifHeight;- var totalImages = frames.length;- var processedImages = 0;- var self = this;- var rs = new ReadableStream({- pull: function pull(controller) {- var frame = frames.shift();- if (!frame) controller.close();- var imgData, rgbComponents, paletteRGB, nq, paletteArray, numberPixels, pixels;- var r, g, b;- var k = 0;- var delay = (frame.delay) ? frame.delay / 10 : 100;- processedImages++;- delay = (processedImages === totalImages && options.extraLastFrameDelay) ? delay + (options.extraLastFrameDelay / 10) : delay;// Add an extra- ctx = self.addFrameDetails(ctx, frame);- imgData = ctx.getImageData(0, 0, width, height);- rgbComponents = dataToRGB(imgData.data, imgData.width, imgData.height);- nq = new NeuQuant(rgbComponents, rgbComponents.length, 15);- paletteRGB = nq.process();- paletteArray = new Uint32Array(componentizedPaletteToArray(paletteRGB));- numberPixels = imgData.height * imgData.width;- pixels = new Uint8Array(imgData.height * imgData.width);- for (var i = 0; i < numberPixels; i++) {- r = rgbComponents[k++];- g = rgbComponents[k++];- b = rgbComponents[k++];- pixels[i] = nq.map(r, g, b);- }- controller.enqueue([0, 0, width, height, pixels, {- palette: paletteArray,- delay: delay- }]);- }- });- return new GifWriter(rs, width, height, {- loop: options.loop || 0 // From GIF: 0 = loop forever, null = not looping, n > 0 = loop n times and stop- });- }-}--// part of neuquant conversion-function componentizedPaletteToArray(paletteRGB) {- var paletteArray = [];- var r, g, b;- for (var i = 0; i < paletteRGB.length; i += 3) {- r = paletteRGB[i];- g = paletteRGB[i + 1];- b = paletteRGB[i + 2];- paletteArray.push(r << 16 | g << 8 | b);- }- return paletteArray;-};-// part of neuquant conversion-function dataToRGB(data, width, height) {- var i = 0;- var length = width * height * 4;- var rgb = [];- while (i < length) {- rgb.push(data[i++]);- rgb.push(data[i++]);- rgb.push(data[i++]);- i++;- }- return rgb;-}diff --git a/web/js/map/animation/gif.js b/web/js/map/animation/gif.jsdeleted file mode 100644index 37fc0559e..000000000--- a/web/js/map/animation/gif.js+++ /dev/null@@ -1,1069 +0,0 @@-import 'jquery-jcrop';-import React from 'react';-import ReactDOM from 'react-dom';-import GifStream from './gif-stream';-import lodashFind from 'lodash/find';-import lodashEach from 'lodash/each';-import lodashRound from 'lodash/round';-import lodashThrottle from 'lodash/throttle';-import lodashCapitalize from 'lodash/capitalize';-import canvg from 'canvg-browser';-import FileSaver from 'file-saver';-import googleTagManager from 'googleTagManager';-import GifResSelection from '../components/animation-widget/gif-panel';-import {- imageUtilGetLayerOpacities,- imageUtilCalculateResolution,- imageUtilGetLayers,- imageUtilGetCoordsFromPixelValues,- imageUtilGetConversionFactor,- bboxWMS13-} from '../modules/image-download/util';-import util from '../util/util';-import wvui from '../ui/ui';-import uiIndicator from '../ui/indicator';-const gifStream = new GifStream();--const conversionConstant = 3.6; // we are saying that the gif compresses each total by about 3.6x-const maxImageDimensionSize = 8200;-const maxGifSize = 250;-const GRATICULE_WARNING =- 'The graticule layer cannot be used to take a snapshot. Would you ' +- 'like to hide this layer?';-const PALETTE_WARNING =- 'One or more layers on the map have been modified (changed palette, ' +- 'thresholds, etc.). These modifications cannot be used to take a ' +- 'snapshot. Would you like to temporarily revert to the original ' +- 'layer(s)?';-const ROTATE_WARNING =- 'Image may not be downloaded when rotated. Would you like to reset rotation?';--const resolutionsGeo = {- values: [- { value: '0.125', text: '30m' },- { value: '0.25', text: '60m' },- { value: '0.5', text: '125m' },- { value: '1', text: '250m' },- { value: '2', text: '500m' },- { value: '4', text: '1km' },- { value: '20', text: '5km' },- { value: '40', text: '10km' }- ]-};-const resolutionsPolar = {- values: [- { value: '1', text: '250m' },- { value: '2', text: '500m' },- { value: '4', text: '1km' },- { value: '20', text: '5km' },- { value: '40', text: '10km' }- ]-};--export function animationGif(models, config, ui) {- var self = {};- var creatingGIF = false;- var jcropAPI = null;- var animationCoordinates = null;- var previousCoords = null;- var animModel = models.anim;- var $progress; // progress bar- var loader;- var showDates = true; // show date stamp- var progressing = false; // if progress bar has started- var panelCase;- var resolution = null;- var imgWidth;- var imgHeight;- var requestSize;- var throttleSetDownloadButton;- var lastRequestedDimensions = {};-- var renderPanel = function(options, mountEl) {- return ReactDOM.render(- React.createElement(GifResSelection, options),- mountEl- );- };-- /*- * sets listeners- *- *- * @method init- * @static- *- * @returns {void}- *- */- self.init = function() {- var options;- models.anim.events.on('gif-click', setImageCoords);- panelCase = document.createElement('div');- panelCase.className = 'gif-dialog';- throttleSetDownloadButton = lodashThrottle(setDownloadButtonClass, 300, {- trailing: true- });-- options = {- resolution: '1',- onSelectionChange: onSelectionChange,- onClick: getGif,- valid: true,- resolutions:- models.proj.selected.id === 'geographic'- ? resolutionsGeo- : resolutionsPolar,- onCheck: onchecked,- startDate: null,- endDate: null,- speed: null,- maxGifSize: maxGifSize,- maxImageDimensionSize: maxImageDimensionSize,- checked: true,- increment: lodashCapitalize(ui.anim.widget.getIncrements())- };- self.reactComponent = renderPanel(options, panelCase);- };-- var getUpdatedProps = function() {- var startDate, endDate;- var state = animModel.rangeState;-- if (models.date.maxZoom < 4) {- startDate = state.startDate.split('T')[0];- endDate = state.endDate.split('T')[0];- } else {- startDate = state.startDate;- endDate = state.endDate;- }-- return {- resolution: resolution,- resolutions:- models.proj.selected.id === 'geographic'- ? resolutionsGeo- : resolutionsPolar,- valid: fileSizeValid(),- fileSizeEstimate: lodashRound(requestSize / conversionConstant, 3),- requestSize: lodashRound(requestSize, 3),- imgHeight: lodashRound(imgHeight, 2),- imgWidth: lodashRound(imgWidth, 2),- startDate: startDate,- endDate: endDate,- speed: lodashRound(state.speed, 2),- increment: lodashCapitalize(ui.anim.widget.getIncrements())- };- };-- var update = function(selectedRes, lonlats) {- if (!animationCoordinates) return;- var numDays, stateObj, dimensions, isGeoProjection;-- isGeoProjection = models.proj.selected.id === 'geographic';- resolution = selectedRes;- stateObj = animModel.rangeState;- numDays = util.getNumberOfDays(- new Date(stateObj.startDate),- new Date(stateObj.endDate),- ui.anim.ui.getInterval()- );-- if (!resolution) {- let currentZoom = Math.round(ui.map.selected.getView().getZoom());- resolution = imageUtilCalculateResolution(- currentZoom,- isGeoProjection,- models.proj.selected.resolutions- );- }- dimensions = getDimensions(lonlats, models.proj.selected.id, resolution);- imgWidth = dimensions[0];- imgHeight = dimensions[1];-- requestSize = calulateFileSize(- resolution,- lonlats[0],- lonlats[1],- numDays,- imgWidth,- imgHeight- );- updatePanel(getUpdatedProps());- throttleSetDownloadButton();- };-- var updatePanel = function(options) {- self.reactComponent.setState(options);- };-- var onSelectionChange = function(selectedRes) {- update(- selectedRes,- imageUtilGetCoordsFromPixelValues(animationCoordinates, ui.map.selected)- );- };-- var fileSizeValid = function() {- return requestSize < maxGifSize &&- imgHeight !== 0 && imgWidth !== 0 &&- imgHeight <= maxImageDimensionSize && imgWidth <= maxImageDimensionSize;- };-- var setDownloadButtonClass = function() {- var $iconCase;- var boo;- $iconCase = $('.wv-dl-gif-bt-case');- if (!$iconCase.length) return;- boo = fileSizeValid();-- if (!boo && !$iconCase.hasClass('disabled')) {- $iconCase.addClass('disabled');- } else if (boo && $iconCase.hasClass('disabled')) {- $iconCase.removeClass('disabled');- }- };-- /*- * Use class to create GIF- *- *- * @method createGIF- * @static- *- * @returns {void}- *- */- self.createGIF = function() {- // set creating GIF status flag- creatingGIF = true;- var imageArra;- var stampWidth;- var build;- var stampProps;- var newImage;- var breakPointOne = 300;- var stampWidthRatio = 4.889;- var stateObj = animModel.rangeState;- var interval = stateObj.speed;- var startDate = stateObj.startDate;- var endDate = stateObj.endDate;-- lastRequestedDimensions.w = animationCoordinates.w;- lastRequestedDimensions.h = animationCoordinates.h;- loader = uiIndicator.loading();- build = function(stamp, dateStamp, stampHeight) {- var buildProgressBar = function() {- $progress = $('<progress />') // display progress for GIF creation- .attr('class', 'wv-gif-progress');- wvui- .getDialog()- .append($progress)- .dialog({- // dialog for progress- title: 'Collecting Images...',- width: 300,- height: 100,- closeText: ''- });- $progress.attr('value', 0);- };- var onGifProgress = function(captureProgress) {- $('#timeline-footer').removeClass('wv-anim-active');- models.anim.rangeState.state = 'off';-- if (!progressing) {- buildProgressBar();- progressing = true;- uiIndicator.hide(loader);- $progress.parent().dialog('option', 'title', 'Creating GIF...'); // set dialog title- }- $progress.attr('value', captureProgress / 100); // before value set, it is in indeterminate state- };-- imageArra = getImageArray(startDate, endDate, interval);- if (!imageArra) {- // won't be true if there are too mant frames- return;- }- gifStream.createGIF(- {- gifWidth: imgWidth,- gifHeight: imgHeight,- images: imageArra,- waterMarkXCoordinate: stampHeight * 0.01, // Margin based on GIF Height- waterMarkYCoordinate: stampHeight * 0.01, // Margin based on GIF Height- waterMarkHeight: stamp.height,- waterMark: stampHeight > 20 ? stamp : null,- waterMarkWidth: stamp.width,- fontSize: dateStamp.fontSize + 'px',- textXCoordinate: dateStamp.x,- textYCoordinate: dateStamp.y, // date location based on Dimensions- textAlign: dateStamp.align, // If textXCoordinate is null this takes precedence- textBaseline: 'top', // If textYCoordinate is null this takes precedence- fontColor: '#fff',- fontWeight: '300',- fontFamily: 'Open Sans, sans-serif',- progressCallback: onGifProgress,- showFrameText: stampHeight > 20,- extraLastFrameDelay: 1000,- text: '',- stroke: {- color: '#000',- pixels: dateStamp.fontSize * 0.05- },- pause: 1- },- onGifComplete- );- };- stampProps = getStampProps(stampWidthRatio, breakPointOne, stampWidth);- newImage = svgToPng(- 'brand/images/wv-logo-w-shadow.svg',- stampProps.stampHeight- );-- build(newImage, stampProps.dateStamp, stampProps.stampHeight);- };-- var svgToPng = function(svgURL, stampHeight) {- var newImage;- var canvasEl = document.createElement('canvas');- var canvgOptions = {- log: false,- ignoreMouse: true,- scaleHeight: stampHeight- };- canvg(canvasEl, svgURL, canvgOptions);- newImage = new Image();- newImage.src = canvasEl.toDataURL('image/png');- newImage.width = canvasEl.width;- newImage.height = canvasEl.height;-- return newImage;- };-- var getStampProps = function(stampWidthRatio, breakPoint, stampWidth) {- var dateStamp = {};- var stampHeight;- var stampHeightByImageWidth;- // Set Logo-stamp dimensions based upon smallest total image dimension- if (lastRequestedDimensions.w < breakPoint) {- stampHeight =- (imgWidth * 0.7) / stampWidthRatio < 60- ? (imgWidth * 0.7) / stampWidthRatio- : 60;- dateStamp.fontSize =- lastRequestedDimensions.h > stampHeight * 1.5- ? lodashRound(stampHeight * 0.65)- : 0;- dateStamp.align = 'left';- dateStamp.x = imgWidth * 0.01;- dateStamp.y = imgHeight - (dateStamp.fontSize + imgHeight * 0.01) - 4;- } else {- stampWidth = imgWidth * 0.4;- stampHeightByImageWidth = stampWidth / stampWidthRatio;- stampHeight =- stampHeightByImageWidth < 20- ? 20- : stampHeightByImageWidth > 60- ? 60- : stampHeightByImageWidth;- dateStamp.fontSize =- lastRequestedDimensions.h > stampHeight * 1.5- ? lodashRound(stampHeight * 0.65)- : 0;- dateStamp.y = imgHeight - (dateStamp.fontSize + imgHeight * 0.01) - 4;- dateStamp.x = imgWidth * 0.01;- dateStamp.align = 'left';- }- return { stampHeight: stampHeight, dateStamp: dateStamp };- };-- /*- * checks if rotation, changed palettes, or graticules- * are active and ask to reset if any are active- *- * @method getGif- * @static- *- * @returns {void}- *- */- var getGif = function() {- // prevent if status flag shows already creating a GIF- if (creatingGIF) {- return;- }- var layers;- // check for rotation, changed palettes, and graticule layers and ask for reset if so-- // ui.anim.stop(); Add this- layers = models.layers.get({- renderable: true- });- if (models.palettes.inUse()) {- wvui.ask({- header: 'Notice',- message: PALETTE_WARNING,- class: 'gif-palette-warning',- onOk: function() {- models.palettes.clear();- getGif();- }- });- return;- }- if (- lodashFind(layers, {- id: 'Graticule'- }) &&- models.proj.selected.id === 'geographic'- ) {- wvui.ask({- header: 'Notice',- message: GRATICULE_WARNING,- class: 'gif-graticule-warning',- onOk: function() {- models.layers.setVisibility('Graticule', false);- self.getGif();- }- });- return;- }- if (ui.map.selected.getView().getRotation() !== 0.0) {- wvui.ask({- header: 'Reset rotation?',- message: ROTATE_WARNING,- class: 'gif-rotation-warning',- onOk: function() {- resetRotation();- // Let rotation finish before reselecting can occur- setTimeout(setImageCoords, 500);- }- });- return;- }- googleTagManager.pushEvent({- 'event': 'GIF_create',- 'layers': {- 'activeCount': models.layers.active.length- },- 'GIF': {- 'resolution': resolution- }- });- self.createGIF();- };-- /*- * retrieves renderable layers- *- * @method getProducts- * @private- *- * @returns {array} array of layer objects- *- */- var getProducts = function(date) {- var layers = [];- var products = models.layers.get({- reverse: true,- renderable: true- });- lodashEach(products, function(layer) {- let layerDate = new Date(date);- if (layer.endDate) {- if (layerDate > new Date(layer.endDate)) return;- }- if (layer.visible && new Date(layer.startDate) <= layerDate) {- layers.push(layer);- } else if (!layer.startDate) {- layers.push(layer);- }- });- return layers;- };-- /*- * Dimenions from zoom & projection- *- * @method getDimensions- * @private- *- * @returns {array} array with dimensions- *- */- var getDimensions = function(lonlat, proj, res) {- var conversionFactor = proj === 'geographic' ? 0.002197 : 256;- return [- Math.round(- Math.abs(lonlat[1][0] - lonlat[0][0]) / conversionFactor / Number(res)- ), // width- Math.round(- Math.abs(lonlat[1][1] - lonlat[0][1]) / conversionFactor / Number(res)- ) // height- ];- };-- /*- * loops through dates and created image- * download urls and pushs them to an- * array- *- * @method getImageArray- * @private- *- * @returns {array} array of jpg urls- *- */- var getImageArray = function(startDate, endDate, interval) {- var a = [];- var fromDate = new Date(startDate);- var toDate = new Date(endDate);- var current = fromDate;- var j = 0;- var src;- var strDate;- var lonlats = imageUtilGetCoordsFromPixelValues(- animationCoordinates,- ui.map.selected- );- var layers;- var proj = models.proj.selected.id;- var opacities;- let crs = models.proj.selected.crs;- let imgFormat = 'image/jpeg';- var products = getProducts();- var intervalAmount = 1;-- let url = 'http://localhost:3002/api/v1/snapshot';- if (config.features.imageDownload && config.features.imageDownload.url) {- url = config.features.imageDownload.url;- util.warn('Redirecting GIF download to: ' + url);- }-- while (current <= toDate) {- j++;- if (models.date.maxZoom > 3) {- strDate = util.toISOStringSeconds(current);- } else {- strDate = util.toISOStringDate(current);- }- products = getProducts(current);-- layers = imageUtilGetLayers(products, proj);- opacities = imageUtilGetLayerOpacities(products);-- let params = [- 'REQUEST=GetSnapshot',- `TIME=${util.toISOStringDate(current)}`,- `BBOX=${bboxWMS13(lonlats, crs)}`,- `CRS=${crs}`,- `LAYERS=${layers.join(',')}`,- `FORMAT=${imgFormat}`,- `WIDTH=${imgWidth}`,- `HEIGHT=${imgHeight}`- ];- if (opacities.length > 0) {- params.push(`OPACITIES=${opacities.join(',')}`);- }-- let dlURL = url + '?' + params.join('&') + `&ts=${Date.now()}`;-- src = util.format(dlURL, strDate);- a.push({- src: src,- text: showDates ? strDate : '',- delay: 1000 / interval- });- if (ui.anim.ui.getInterval() === 'minute') {- intervalAmount = 15;- } else {- intervalAmount = 1;- }- current = util.dateAdd(current, ui.anim.ui.getInterval(), intervalAmount);- if (j > 40) {- // too many frames- showUnavailableReason();- uiIndicator.hide(loader);-- return false;- }- }- return a;- };-- /*- * Thows an alert notifies the user- * that too many frames were selected- *- * @method showUnavailableReason- * @private- *- * @returns {void}- *- */- var showUnavailableReason = function() {- var headerMsg =- "<h3 class='wv-data-unavailable-header'>GIF Not Available</h3>";- var bodyMsg =- 'Too many frames were selected. Please request less than 40 frames if you would like to generate a GIF';- var callback = function() {- $('#timeline-footer').toggleClass('wv-anim-active');- };- wvui.notify(headerMsg + bodyMsg, 'Notice', 600, callback);- };-- /*- * resets map rotation to- * zero degrees- *- * @method resetRotation- * @private- *- * @returns {void}- *- */- var resetRotation = function() {- ui.map.selected.getView().animate({- duration: 400,- rotation: 0- });- };-- /*- * Handles GIF generater conpletion- *- * @method onGifComplete- * @callback- *- * @param obj {object} gifShot GIF-complete- * object- *- * @returns {void}- *- */- var onGifComplete = function(obj) {- // reset creating GIF status flag- creatingGIF = false;- // callback function for when image is finished- $('#timeline-footer').removeClass('wv-anim-active');- models.anim.rangeState.state = 'off';- if (!obj.error) {- const blob = obj.blob;- $progress.remove();- progressing = false;- var animatedImage = document.createElement('img');- const blobURL = URL.createObjectURL(blob);- animatedImage.src = blobURL;- animatedImage.width =- lastRequestedDimensions.w > window.innerWidth - 198- ? window.innerWidth - 198- : lastRequestedDimensions.w;- animatedImage.height =- lastRequestedDimensions.h > window.innerHeight - 120- ? window.innerHeight - 120- : lastRequestedDimensions.h;- var dlURL = util.format(- 'nasa-worldview-{1}-to-{2}.gif',- animModel.rangeState.startDate,- animModel.rangeState.endDate- );- var downloadSize = lodashRound((blob.size / 1024) * 0.001, 2);-- // Create download link and apply button CSS- var $download = $(- '<button><span class=ui-button-text>Download</span></button>'- )- .attr('class', 'wv-button')- .hover(- function() {- $(this).addClass('ui-state-hover');- },- function() {- $(this).removeClass('ui-state-hover');- }- )- .click(function(e) {- e.preventDefault();- FileSaver.saveAs(blob, dlURL);- googleTagManager.pushEvent({- 'event': 'GIF_download',- 'GIF': {- 'downloadSize': downloadSize,- 'increments': ui.anim.widget.getIncrements(),- 'frameSpeed': animModel.rangeState.speed- }- });- });-- var $catalog =- "<div class='gif-results-dialog' style='height: " +- animatedImage.height +- "px; min-height: 210px;' >" +- '<div>' +- '<div><b>' +- 'Size: ' +- '</b></div>' +- '<div>' +- downloadSize +- ' MB' +- '</div>' +- '</div>' +- '<div>' +- '<div><b>' +- 'Speed: ' +- '</b></div>' +- '<div>' +- animModel.rangeState.speed +- ' fps' +- '</div>' +- '</div>' +- '<div>' +- '<div><b>' +- 'Date Range: ' +- '</b></div>' +- '<div>' +- animModel.rangeState.startDate +- '</div>' +- '<div>' +- ' - ' +- '</div>' +- '<div>' +- animModel.rangeState.endDate +- '</div>' +- '</div>' +- '<div>' +- '<div><b>' +- 'Increments: ' +- '</b></div>' +- '<div>' +- lodashCapitalize(ui.anim.widget.getIncrements()) +- '</div>' +- '</div>' +- '</div>';- var $dialogBodyCase = $('<div></div>');- $dialogBodyCase.addClass('gif-results-dialog-case clearfix');- $dialogBodyCase.css('padding', '10px 0');- $dialogBodyCase.append(animatedImage);- $dialogBodyCase.append($catalog);- // calculate the offset of the dialog position based on image size to display it properly- // only height needs to be adjusted to center the dialog- var posWidth = (lastRequestedDimensions.w * 1) / window.innerWidth;- var posHeight = (lastRequestedDimensions.h * 50) / window.innerHeight;- var atString =- 'center-' +- posWidth.toFixed() +- '% center-' +- posHeight.toFixed() +- '%';-- // Create a dialog over the view and place the image there- var $imgDialog = wvui- .getDialog()- .append($dialogBodyCase)- .append($download);- $imgDialog.dialog({- dialogClass: 'wv-panel wv-gif-results',- title: 'Your GIF',- width: animatedImage.width + 204,- resizable: false,- maxWidth: window.innerWidth,- maxHeight: window.innerHeight,- closeText: '',- close: function() {- $imgDialog.find('img').remove();- models.anim.rangeState.state = 'on';- $('#timeline-footer').toggleClass('wv-anim-active');- },- position: {- // based on image size- my: 'center center',- at: atString,- of: window- }- });- } else {- var headerMsg =- "<h3 class='wv-data-unavailable-header'>GIF Not Available</h3>";- var bodyMsg =- 'One or more of the frames requested was unable to be processed';- uiIndicator.hide(loader);- var callback = function() {- $('#timeline-footer').toggleClass('wv-anim-active');- };- wvui.notify(headerMsg + bodyMsg, 'Notice', 600, callback);- }- };-- /*- * Builds selector dialog- *- * @method getSelectorDialog- * @private- *- * @param width {number}- *- * @returns {JQuery} Selector diaglog element- *- */- var getSelectorDialog = function(width) {- var $dialogBox;- $dialogBox = wvui.getDialog();- $dialogBox.html(panelCase);- $dialogBox.css({- paddingBottom: '10px'- });- $dialogBox.dialog({- dialogClass: 'wv-panel wv-image',- title: 'Create An Animated GIF',- height: 'auto',- width: width,- minHeight: 40,- minWidth: 287,- resizable: false,- show: {- effect: 'slide',- direction: 'right'- },- position: {- my: 'left top',- at: 'right+10 top',- of: $('.jcrop-tracker')- },- closeText: '',- close: onCloseSelector- });- return $dialogBox;- };-- var onCloseSelector = function() {- $('#wv-map').insertAfter('#productsHolder'); // retain map element before disabling jcrop- jcropAPI.destroy();- $('#timeline-footer').toggleClass('wv-anim-active');- if (models.proj.selected.id === 'geographic') {- ui.map.events.trigger('selectiondone');- }- };-- /*- * uses resolution and dimension to- * calculates size of selected area- *- * @method calulateFileSize- * @private- *- * @param c {object} dimension object- *- * @returns {number} Size of frame- *- */- var calulateFileSize = function(- imgRes,- lonlat1,- lonlat2,- numDays,- imgWidth,- imgHeight- ) {- var conversionFactor;-- conversionFactor = imageUtilGetConversionFactor(models.proj.selected.id);- resolution = imgRes;- imgWidth = Math.round(- Math.abs(lonlat2[0] - lonlat1[0]) / conversionFactor / Number(imgRes)- );- imgHeight = Math.round(- Math.abs(lonlat2[1] - lonlat1[1]) / conversionFactor / Number(imgRes)- );-- return ((imgWidth * imgHeight * 24) / 8388608).toFixed(2) * numDays;- };-- /*- * removes jquery JCrop- *- * @method removeCrop- * @private- *- * @param c {object} dimension object- *- * @returns {void}- *- */- var removeCrop = function() {- $('#wv-map').insertAfter('#productsHolder'); // retain map element before disabling jcrop- animationCoordinates = undefined;- jcropAPI.destroy();- if (models.proj.selected.id === 'geographic') {- ui.map.events.trigger('selectiondone');- }- };-- /*- * checkBox event handler- *- * @method onchecked- * @private- *- * @param e {Jquery} event object- *- * @returns {void}- *- */- var onchecked = function(showDatesBoolean) {- showDates = showDatesBoolean;- };-- /*- * Sets diaglog width && location- *- * @method setDialogWidth- * @private- *- * @param $dialog {Jquery} dialog- * @param width {number} JCrop selector width- *- * @returns {void}- *- */- var setDialogWidth = function($dialog, width) {- var $parent;- if (width < 287) {- width = 287;- }- if ($dialog) {- $parent = $dialog.parent();- $parent.position({- my: 'left top',- at: 'right+10 top',- collision: 'flipfit',- of: $('.jcrop-tracker')- });- }- };-- /*- * Adjusts download icon size- *- * @method setIconFontSize- * @private- *- * @param $el {Jquery} icon element- * @param width {number} JCrop selector width- *- * @returns {void}- *- */- var setIconFontSize = function($el, width) {- if (!$el) {- return;- }- var fontSize = Math.abs(width / 4); // Font size is 25% width- fontSize = fontSize < 30 ? 30 : fontSize > 100 ? 100 : fontSize; // Set max and min font-size-- $el.css('font-size', fontSize);- };-- var onBoundingBoxChange = function(c, $dialog, $dlButton) {- animationCoordinates = c;-- if (c.h !== 0 && c.w !== 0) {- // don't save coordinates if empty selection- previousCoords = c;- }- // var dataSize = calcSize(c);- // Update the gif selection dialog-- setDialogWidth($dialog, c.w);- setIconFontSize($dlButton, c.w);- };-- /*- * Initializes and sets callbacks for- * Jcrop selector- *- * @method setImageCoords- * @private- *- * @returns {void}- *- */- var setImageCoords = function() {- var starterWidth;- var $dlButton;- var $dialog;- // Set JCrop selection- if (previousCoords === null || previousCoords === undefined) {- previousCoords = [- $(window).width() / 2 - 100,- $(window).height() / 2 - 100,- $(window).width() / 2 + 100,- $(window).height() / 2 + 100- ];- } else {- previousCoords = [- previousCoords.x,- previousCoords.y,- previousCoords.x2,- previousCoords.y2- ];- }-- if (models.proj.selected.id === 'geographic') {- ui.map.events.trigger('selecting');- }- starterWidth = previousCoords[0] - previousCoords[2];- // Start the image cropping. Show the dialog- $('#wv-map').Jcrop(- {- bgColor: 'black',- bgOpacity: 0.3,- fullScreen: true,- setSelect: previousCoords,- onSelect: function(e) {- onBoundingBoxChange(e, $dialog, $dlButton);- },- onChange: function(e) {- onBoundingBoxChange(e, $dialog, $dlButton);- update(- resolution,- imageUtilGetCoordsFromPixelValues(- animationCoordinates,- ui.map.selected- )- );- },- onRelease: function() {- removeCrop();- if ($dialog) {- wvui.close();- }- }- },- function() {- var $tracker;- $dlButton =- "<div class='wv-dl-gif-bt-case'>" +- "<i class='fa fa-download'>" +- '</div>';- jcropAPI = this;- $('#timeline-footer').toggleClass('wv-anim-active');- $dialog = getSelectorDialog(342);- $tracker = this.ui.selection.find('.jcrop-tracker');- $tracker.append($dlButton);- $dlButton = $('.wv-dl-gif-bt-case i');- setIconFontSize($dlButton, starterWidth);- $dlButton.on('click', getGif);- }- );-- update(- null,- imageUtilGetCoordsFromPixelValues(animationCoordinates, ui.map.selected)- );- };- self.init();- return self;-}diff --git a/web/js/map/animation/model.js b/web/js/map/animation/model.jsdeleted file mode 100644index 66c4908c2..000000000--- a/web/js/map/animation/model.js+++ /dev/null@@ -1,161 +0,0 @@-import util from '../util/util';--export function animationModel(models, config) {- // state.a is now an object, check input and set values- var self = {};- self.delay = 500;- self.events = util.events();-- self.animationState = {- active: false,- speed: 10,- loop: false,- reverse: false- };-- /*- * Pulls state.a from permalink- * on page load- *- * @method load- * @static- *- * @param state {object} state object- * @param errors {object} error object- * @returns {void}- *- */- self.load = function(state, errors) {- self.rangeState = self.rangeState || {};- // self.rangeState.playing = false;- // if(state.a) {- // self.rangeState.state = 'on';- // attributes = state.a.attributes;- // attributes.forEach(function(attr) {- // self.rangeState[attr.id] = attr.value;- // });- // }-- if (state.ab) {- self.rangeState.state = state.ab;- }- if (state.as && state.ae) {- if (state.ae.length >= 10 && state.as.length >= 10) {- self.rangeState.startDate = state.as;- self.rangeState.endDate = state.ae;- }- }- if (state.av) {- self.rangeState.speed = Number(state.av);- }- if (state.al) {- self.rangeState.loop = Boolean(state.al);- }- return self;- };-- /*- * Toggles state object between- * on and off- *- * @method toggleActive- * @static- *- * @returns {void}- *- */- self.toggleActive = function() {- if (self.rangeState.state === 'off') {- self.rangeState.state = 'on';- } else {- self.rangeState.state = 'off';- }- };-- /*- * Activates state object- *- * @method activate- * @static- *- * @returns {void}- *- */- self.activate = function() {- self.rangeState.state = 'on';- };-- /*- * Deactivate state object- *- * @method deactivate- * @static- *- * @returns {void}- *- */- self.deactivate = function() {- self.rangeState.state = 'off';- };-- /*- * saves animation state to permalink- *- * @method save- * @static- *- * @returns {void}- *- */-- self.add = function(arra) {- // var updatedState = _.clone(self.state);- // arra.forEach(function(prop) {- // updatedState[prop.id] = prop.value;- // });- // self.animationState = updatedState;- };-- /*- * saves animation state to permalink- *- * @method save- * @static- *- * @returns {void}- *- */- self.save = function(state) {- var rangeState = self.rangeState;- // state.a = state.a || [];- // newState = {id: rangeState.state};- // newState.attributes = [];- if (rangeState.state) {- state.ab = rangeState.state;- state.as = rangeState.startDate;- state.ae = rangeState.endDate;- state.av = String(rangeState.speed);- state.al = String(rangeState.loop);- }- // newState.attributes.push(- // {- // id:'startDate',- // value: rangeState.startDate- // },- // {- // id:'endDate',- // value: rangeState.endDate- // },- // {- // id:'speed',- // value: rangeState.speed- // },- // {- // id:'loop',- // value: rangeState.loop- // }- // );- // state.a.push(newState);- };- return self;-}diff --git a/web/js/map/animation/ui.js b/web/js/map/animation/ui.jsdeleted file mode 100644index e0b20fb0f..000000000--- a/web/js/map/animation/ui.js+++ /dev/null@@ -1,812 +0,0 @@-import lodashIsEmpty from 'lodash/isEmpty';-import Queue from 'promise-queue';-import util from '../util/util';-import uiIndicator from '../ui/indicator';-import {- PLAY_ANIMATION,- TOGGLE_GIF,- UPDATE_START_DATE,- UPDATE_END_DATE-} from '../../modules/animation/constants';-import { changeEndDate } from '../../modules/animation/actions';--export function animationUi(models, ui, store) {- var self = {};- self.events = util.events();- var dateModel = models.date;- var animModel = models.anim;- var queueLength;- var queue = new Queue(5, Infinity);- var zooms = ['custom', 'year', 'month', 'day', 'hour', 'minute'];- var preload = {};- var preloadArray;- var inQueue;- var pastDates;- var loader;-- const subscribeToStore = function() {- const state = store.getState();- const action = state.lastAction;- switch (action.type) {- case PLAY_ANIMATION:- return self.onPushedPlay();-- case TOGGLE_GIF:- case UPDATE_START_DATE:- case UPDATE_END_DATE:- case modalConstants.OPEN_CUSTOM:- case modalConstants.OPEN_BASIC:- case layerConstants.REMOVE_LAYER:- case sidebarConstants.CHANGE_TAB:- return self.refreshState();- case SELECT_DATE:- return self.dateChange();- }- };- /*- * sets listeners- *- *- * @method init- * @static- *- * @returns {void}- *- */- self.init = function() {- self.refreshState();- store.subscribe(subscribeToStore);- animModel.events.on('play', self.onPushedPlay);- animModel.events.on('gif-click', self.refreshState);- animModel.events.on('datechange', self.refreshState);- animModel.events.on('toggle-widget', self.refreshState);- if (models.proj) {- models.proj.events.on('select', self.refreshState);- }- if (models.palettes) {- models.palettes.events.on('update', self.refreshState);- }- if (models.data) {- models.data.events.on('activate', self.refreshState);- models.date.events.on('interval-change', self.refreshState);- models.date.events.on('select', self.dateChange);- }- if (ui.map) {- ui.map.events.on('added-layer', self.refreshState);- }- };-- /*- * If there is a change of date- * and the animiation is not playing- * the amin.ui states will be refreshed- *- * @method dateChange- * @static- *- * @returns {void}- *- */- self.dateChange = function() {- if (!self.state.playing) {- self.refreshState();- }- };-- /*- * Resets amin.ui object- * and variable states- *- * @method refreshState- * @static- *- * @returns {void}- *- */-- self.refreshState = function() {- preloadArray = [];- preload = {};- pastDates = {};- inQueue = {};- queueLength = 10; // Default length- self.state = {- playing: false,- playIndex: self.getStartDate(),- supportingCustomLayers: self.hasCustomLayers()- };- animModel.rangeState.playing = false;- animModel.events.trigger('change');- uiIndicator.hide(loader);- uiIndicator._hide(loader);- };-- /*- * Determines whether to start at- * current date or to start at the- * selected start date- *- * @method getStartDate- * @static- *- * @returns {string} ISO string Date- *- */- self.getStartDate = function() {- // get index+1 of date zoom 'yearly', 'monthly', 'daily', '10-Minute'- let dateSelectedZoom = models.date.selectedZoom || 1;- var state;- var endDate;- var startDate;- var currentDate;- state = animModel.rangeState;- endDate = util.parseDateUTC(state.endDate);- startDate = util.parseDateUTC(state.startDate);- // if not index+1 of 4 ('10-Minute'), zero out start/end times and resave-- // # causes UTC zeroing of dates in date model - need to rework if this- // # functionality is still going to be used or handle zeroing out- // # at actual layer building only- // if (dateSelectedZoom < 4) {- // let zeroDate = dateModel.selected;- // debugger;- // util.clearTimeUTC(zeroDate);- // util.clearTimeUTC(startDate);- // dateModel.selected = zeroDate;- // }- let activeDate = dateModel.activeDate; // determine if selected or selectedB- currentDate = dateModel[activeDate];- if (currentDate > startDate && self.nextDate(currentDate) < endDate) {- return util.toISOStringSeconds(self.nextDate(currentDate));- }- return util.toISOStringSeconds(startDate);- };-- /*- * Handles a play click event- *- * @method onPushedPlay- * @static- *- * @returns {void}- *- */-- self.onPushedPlay = function() {- queueLength = self.setQueueLength();- self.checkQueue(queueLength, self.state.playIndex);- self.checkShouldPlay();- };-- /**- * Returns the queueLength based on the play speed selected- * @method setQueueLength- * @static- *- * @return {number} The queueLength amount- */- self.setQueueLength = function() {- var speed = animModel.rangeState.speed;- switch (true) {- case speed > 8 && speed <= 10:- queueLength = 40;- break;- case speed > 7 && speed <= 8:- queueLength = 32;- break;- case speed > 5 && speed <= 7:- queueLength = 24;- break;- case speed > 3 && speed <= 5:- queueLength = 16;- break;- case speed > 0 && speed <= 3:- queueLength = 10;- break;- }- return queueLength;- };-- /*- * retrieves the current timeline zoom- *- * @method getInterval- * @static- *- * @returns {string} Zoom increment- *- */- self.getInterval = function() {- return zooms[models.date.interval];- };-- /*- * Gets next date based on current- * increments- *- * @method nextDate- * @static- *- * @param date {object} JS date obj- *- * @returns {object} JS Date- *- */-- // # need to change subdaily argument for custom intervals - rework for all zoom levels presumably- self.nextDate = function(date) {- // console.log(date)- let customSelected = models.date.customSelected;- let interval;- let delta;- if (customSelected) {- interval = zooms[Number(models.date.customInterval)] || zooms[3];- if (interval === 'custom') {- interval = zooms[models.date.selectedZoom];- }- delta = models.date.customDelta || 1;- } else {- interval = self.getInterval();- delta = 1;- }- return util.dateAdd(date, interval, delta);- };-- /*- * Gets next date based on current- * increments- *- * @method nextDate- * @static- *- * @param date {object} JS date obj- *- * @returns {object} JS Date- *- */- self.addDate = function(date) {- self.addToInQueue(date);- queue- .add(function() {- if (- animModel.rangeState.state === 'on' &&- animModel.rangeState.playing- ) {- return ui.map.promiseDay(date);- } else {- self.clearCache();- uiIndicator.hide(loader);- }- })- .then(function(date) {- if (- animModel.rangeState.state === 'on' &&- animModel.rangeState.playing- ) {- self.addDateToCache(date);- self.shiftCache();- self.checkQueue(queueLength, self.state.playIndex);- self.checkShouldPlay();- }- });- };-- /*- * Add date to loading Queue- * obj- *- * @method addToInQueue- * @static- *- * @param date {object} JS date obj- *- * @returns {void}- *- */- self.addToInQueue = function(date) {- var strDate = util.toISOStringSeconds(date);- inQueue[strDate] = date;- preloadArray.push(strDate);- };-- /*- * removes date from inQueue obj- * and adds it to the preloaded- * obj- *- * @method addDateToCache- * @static- *- * @param date {object} JS date obj- *- * @returns {void}- *- */- self.addDateToCache = function(date) {- var strDate = util.toISOStringSeconds(date);- preload[strDate] = date;- delete inQueue[strDate];- };-- /*- * removes item from cache after it has- * been played and quelimit reached- *- *- * @method shiftCache- * @static- *- * @returns {void}- *- */- self.shiftCache = function() {- var key;- if (- preload[preloadArray[0]] &&- util.objectLength(preload) > queueLength + queueLength / 2 + 1 &&- pastDates[preloadArray[0]] &&- !self.isInToPlayGroup(preloadArray[0])- ) {- key = preloadArray.shift();- delete preload[key];- delete pastDates[key];- }- };-- /*- * checks if this date is in array of- * dates that need to play in future- * within buffer length- *- *- * @method isInToPlayGroup- * @static- *- * @param testDate {string} JS date string- *- * @returns {boolean}- *- */- self.isInToPlayGroup = function(testDate) {- var loop = animModel.rangeState.loop;- var i = 0;- var day = new Date(self.state.playIndex);- var startDate = new Date(animModel.rangeState.startDate);- var endDate = new Date(animModel.rangeState.endDate);- // console.log(startDate, endDate);- var jsTestDate = new Date(testDate);- while (i < queueLength) {- if (self.nextDate(day) > endDate) {- if (!loop) {- return false;- }- day = self.setNewDate(day, startDate);- } else {- day = self.nextDate(day);- }- if (day.valueOf() === jsTestDate.valueOf()) {- return true;- }- i++;- }- return false;- };-- /*- * Clears precache- *- * @method clearCache- * @static- *- *- * @returns {void}- *- */- self.clearCache = function() {- preload = {};- preloadArray = [];- };-- /*- * Determines what dates should- * be queued- *- * @method checkQueue- * @static- *- * @param bufferLength {number} JS date string- * @param index {string} Date string- * @returns {void}- *- */- self.checkQueue = function(bufferLength, index) {- var currentDate;- var startDate = util.parseDateUTC(animModel.rangeState.startDate);- var endDate = util.parseDateUTC(animModel.rangeState.endDate);-- var lastToQueue;- if (!animModel.rangeState.playing) {- return self.refreshState();- }- currentDate = util.parseDateUTC(index);- lastToQueue = self.getLastBufferDateStr(currentDate, startDate, endDate);- if (!preloadArray[0] && !inQueue[index]) {- self.initialPreload(currentDate, startDate, endDate, lastToQueue);- } else if (- !preload[lastToQueue] &&- !inQueue[lastToQueue] &&- !self.state.supportingCustomLayers- ) {- // if last preload date doesn't exist- self.addItemToQueue(currentDate, startDate, endDate);- } else if (self.state.supportingCustomLayers && preloadArray[0]) {- self.customQueuer(currentDate, startDate, endDate);- }- };-- /*- * Checks to see if custom layers are- * active- *- * @method hasCustomLayers- * @static- *- * @returns {boolean}- *- */- self.hasCustomLayers = function() {- var layer;- var layers = models.layers.get();-- for (var i = 0, len = layers.length; i < len; i++) {- layer = layers[i];- if (!lodashIsEmpty(models.palettes.isActive(layer.id)) && layer.visible) {- return true;- }- }- return false;- };-- /*- * Custom date queuer created for- * custom colormaps- *- * @method customQueuer- * @static- *- * @param currentDate {object} JS date- * @param startDate {object} JS date- * @param endDate {object} JS date- *- * @returns {void}- *- */- self.customQueuer = function(currentDate, startDate, endDate) {- var nextDateStr;- var nextDate = self.nextDate(currentDate);- if (nextDate > endDate) {- nextDate = self.setNewDate(nextDate, startDate);- }-- nextDateStr = util.toISOStringSeconds(nextDate);-- if (!preload[nextDateStr] && !inQueue[nextDateStr] && !self.state.playing) {- self.clearCache();- self.checkQueue(queueLength, self.state.playIndex);- }- };-- /*- * adds dates to precache queuer- *- * @method initialPreload- * @static- *- * @param currentDate {object} JS date- * @param startDate {object} JS date- * @param endDate {object} JS date- * @param lastToQueue {string} date String- *- * @returns {void}- *- */- self.initialPreload = function(currentDate, startDate, endDate, lastToQueue) {- var day = currentDate;- queueLength = self.getQueueLength(startDate, endDate);- if (queueLength <= 1) {- // if only one frame will play just move to that date- dateModel.select(startDate);- animModel.rangeState.playing = false;- setTimeout(function() {- self.refreshState();- }, 100);- return;- }- for (var i = 0; i < queueLength; i++) {- self.addDate(day);- day = self.getNextBufferDate(day, startDate, endDate);- if (util.toISOStringSeconds(day) === lastToQueue) {- self.addDate(day);- loader = uiIndicator.loading();- return;- } else if (- util.toISOStringSeconds(day) === util.toISOStringSeconds(currentDate)- ) {- queueLength = i;- loader = uiIndicator.loading();- return;- }- }- loader = uiIndicator.loading();- };-- /*- * calculates buffer length if- * date array length is less than- * default queueLength- *- * @method getQueueLength- * @static- *- * @param startDate {object} JS date- * @param endDate {object} JS date- *- * @returns {number} new buffer length- *- */- self.getQueueLength = function(startDate, endDate) {- var day = startDate;- var i = 0;- while (i < queueLength) {- i++;- day = self.nextDate(day);- if (day > endDate) {- return i;- }- }- return i;- };-- /*- * Verifies that date is- * valid and adds it to queuer- *- * @method addItemToQueue- * @static- *- * @param startDate {object} JS date- * @param endDate {object} JS date- *- * @returns {void}- *- */- self.addItemToQueue = function(currentDate, startDate, endDate) {- var nextDate = self.getNextBufferDate(currentDate, startDate, endDate);- var nextDateStr = util.toISOStringSeconds(nextDate);-- if (- !inQueue[nextDateStr] &&- !preload[nextDateStr] &&- nextDate <= endDate &&- nextDate >= startDate- ) {- self.addDate(nextDate);- self.checkQueue(queueLength, self.state.playIndex);- }- };-- /*- * gets next date to add to- * queue- *- * @method addItemToQueue- * @static- *- * @param currentDate {object} JS date- * @param startDate {object} JS date- * @param endDate {object} JS date- *- * @returns {object} JS Date- *- */- self.getNextBufferDate = function(currentDate, startDate, endDate) {- var lastInBuffer = util.parseDateUTC(preloadArray[preloadArray.length - 1]);- var nextDate = self.nextDate(lastInBuffer);- if (lastInBuffer >= endDate || self.nextDate(lastInBuffer) > endDate) {- return self.setNewDate(nextDate, startDate);- }- return self.nextDate(lastInBuffer);- };-- /*- * Gets the last date that should be added- * to the queuer- *- * @method getLastBufferDateStr- * @static- *- * @param currentDate {object} JS date- * @param startDate {object} JS date- * @param endDate {object} JS date- *- * @returns {string} Date string- *- */- self.getLastBufferDateStr = function(currentDate, startDate, endDate) {- var day = currentDate;- var loop = animModel.rangeState.loop;- var i = 1;-- while (i < queueLength) {- if (self.nextDate(day) > endDate) {- if (!loop) {- return util.toISOStringSeconds(day);- }- day = self.setNewDate(day, startDate);- } else {- day = self.nextDate(day);- }- i++;- }- return util.toISOStringSeconds(day);- };-- /*- * Gets the last date that should be added- * to the queuer- *- * @method checkShouldLoop- * @static- *- * @param playIndexJSDate {object} JS date- * that is currently being shown- *- * @returns {void}- *- */- self.checkShouldLoop = function(playIndexJSDate) {- if (animModel.rangeState.loop) {- self.shiftCache();- self.state.playIndex = util.toISOStringSeconds(- self.setNewDate(- playIndexJSDate,- new Date(animModel.rangeState.startDate)- )- );- setTimeout(function() {- self.checkShouldPlay();- self.checkQueue(queueLength, self.state.playIndex);- }, 1000);- } else {- self.refreshState();- }- };-- /*- * Gets the last date that should be added- * to the queuer- *- * @method checkShouldLoop- * @static- *- * @param playIndexJSDate {object} JS date- * that is currently being shown- *- * @returns {void}- *- */- self.checkShouldPlay = function() {- var currentDate = util.parseDateUTC(self.state.playIndex);- var endDate = util.parseDateUTC(animModel.rangeState.endDate);- var startDate = util.parseDateUTC(animModel.rangeState.startDate);- if (self.state.playing || !animModel.rangeState.playing) {- return false;- }-- if (preload[self.getLastBufferDateStr(currentDate, startDate, endDate)]) {- self.play(self.state.playIndex);- return;- }- if (- self.state.supportingCustomLayers &&- preload[self.state.playIndex] &&- lodashIsEmpty(inQueue)- ) {- self.play(self.state.playIndex);- return;- }- self.shiftCache();- };-- /*- * removes loader and starts the- * animation- *- * @method play- * @static- *- * @param index {string} date string- *- * @returns {void}- *- */- self.play = function(index) {- self.state.playing = true;- uiIndicator.hide(loader);- uiIndicator._hide(loader);- self.animate(index);- if (document.hidden) {- self.state.playing = false;- }- };-- /*- * Gets date to start on when animation- * is being looped- *- * @method setNewDate- * @static- *- * @param date {number} JS Date- * @param newDate {number} JS Date- *- * @returns {void}- *- */- self.setNewDate = function(date, newDate) {- return newDate;- };-- /*- * function that loops through frames- * at a specified time interval- *- * @method animate- * @static- *- * @param index {string} Date string- * @returns {void}- *- */- self.animate = function(index) {- var interval;- var playIndex = index;- var playIndexJSDate;- var endDate = util.parseDateUTC(animModel.rangeState.endDate);- var player = function() {- self.shiftCache();- self.checkQueue(queueLength, playIndex);-- dateModel.select(util.parseDateUTC(playIndex));- pastDates[playIndex] = util.parseDateUTC(playIndex); // played record- self.state.playIndex = playIndex;- playIndex = util.toISOStringSeconds(self.nextDate(new Date(playIndex)));- playIndexJSDate = new Date(playIndex);- if (playIndexJSDate > endDate) {- clearInterval(interval);- self.state.playing = false;- self.checkShouldLoop(playIndexJSDate);- return;- }- if (!animModel.rangeState.playing || !preload[playIndex]) {- clearInterval(interval);- self.state.playing = false;- if (!preload[playIndex] && animModel.rangeState.playing) {- // Still playing, add loader- loader = uiIndicator.loading();- self.shiftCache();- self.checkQueue(queueLength, self.state.playIndex);- } else {- self.refreshState();- }- return;- }-- self.checkQueue(queueLength, self.state.playIndex);- interval = setTimeout(player, 1000 / animModel.rangeState.speed);- };- interval = setTimeout(player, animModel.rangeState.speed);- };- self.init();- return self;-}diff --git a/web/js/map/data/model.test.js b/web/js/map/data/model.test-old.jssimilarity index 100%rename from web/js/map/data/model.test.jsrename to web/js/map/data/model.test-old.jsdiff --git a/web/js/modules/core/actions.js b/web/js/modules/core/actions.jsindex 585e8b80d..6620c31fd 100644--- a/web/js/modules/core/actions.js+++ b/web/js/modules/core/actions.js@@ -40,7 +40,7 @@ export function requestAction(export function startRequest(actionName, id) {return {type: `${actionName}_START`,- id: id+ ...(!!id && { id })};}@@ -48,7 +48,7 @@ export function fetchSuccess(actionName, response, id) {return {type: `${actionName}_SUCCESS`,response: response,- id: id+ ...(!!id && { id })};}// export function fetchTimeout(actionName, error, id) {@@ -61,6 +61,6 @@ export function fetchFailure(actionName, error, id) {return {type: `${actionName}_FAILURE`,error: error,- id: id+ ...(!!id && { id })};}diff --git a/web/js/modules/link/actions.test.js b/web/js/modules/link/actions.test.jsindex f80972926..91e0dfd94 100644--- a/web/js/modules/link/actions.test.js+++ b/web/js/modules/link/actions.test.js@@ -3,11 +3,9 @@ import thunk from 'redux-thunk';import fetchMock from 'fetch-mock';import * as actions from './actions';import * as constants from './constants';-const middlewares = [thunk];const mockStore = configureMockStore(middlewares);const ERROR_MESSAGE = 'There was an error';-// throw new Error(ERROR_MESSAGE);describe('Short Link request action', () => {afterEach(() => {diff --git a/web/js/modules/link/reducers.js b/web/js/modules/link/reducers.jsindex 378d48568..f7b85086e 100644--- a/web/js/modules/link/reducers.js+++ b/web/js/modules/link/reducers.js@@ -2,7 +2,7 @@ import { REQUEST_SHORT_LINK, UPDATE_PERMALINK } from './constants';import { requestReducer } from '../core/reducers';import { assign as lodashAssign } from 'lodash';-const defaultLinkState = {+export const defaultLinkState = {queryString: ''};diff --git a/web/js/modules/link/reducers.test.js b/web/js/modules/link/reducers.test.jsindex 5a500322d..db70662bd 100644--- a/web/js/modules/link/reducers.test.js+++ b/web/js/modules/link/reducers.test.js@@ -1,4 +1,4 @@-import { linkReducer, deafultLinkState, shortLink } from './reducers';+import { linkReducer, defaultLinkState, shortLink } from './reducers';import * as constants from './constants';import { defaultRequestState } from '../core/reducers';@@ -32,9 +32,9 @@ describe('shortLink reducer', () => {});});});-describe('notificationsReducer', () => {+describe('linkReducer', () => {test('should return the initial state', () => {- expect(linkReducer(undefined, {})).toEqual(deafultLinkState);+ expect(linkReducer(undefined, {})).toEqual(defaultLinkState);});test(constants.UPDATE_PERMALINK +diff --git a/web/js/modules/notifications/actions.test.js b/web/js/modules/notifications/actions.test.jsindex 3a7b44dd8..12bd3bb27 100644--- a/web/js/modules/notifications/actions.test.js+++ b/web/js/modules/notifications/actions.test.js@@ -6,7 +6,6 @@ import * as constants from './constants';const middlewares = [thunk];const mockStore = configureMockStore(middlewares);const ERROR_MESSAGE = 'There was an error';-describe('Notification fetch action', () => {afterEach(() => {fetchMock.restore();diff --git a/web/js/modules/projection/util.js b/web/js/modules/projection/util.jsindex f4e28fe74..d0a14d531 100644--- a/web/js/modules/projection/util.js+++ b/web/js/modules/projection/util.js@@ -6,6 +6,7 @@ export function getProjInitialState(config) {config,`projections.${config.defaults.projection}`);+ console.log('selected' + selected);return {id: selected ? selected.id : 'geographic',selected: selected || {}diff --git a/web/js/modules/projection/util.test.js b/web/js/modules/projection/util.test.jsnew file mode 100644index 000000000..58a11307a--- /dev/null+++ b/web/js/modules/projection/util.test.js@@ -0,0 +1,46 @@+import { mapLocationToProjState, getProjInitialState } from './util';++const proj = {+ id: 'some-test-projection'+};+const config = {+ defaults: {+ projection: 'some-test-projection'+ },+ projections: {+ 'some-test-projection': proj+ }+};+test('getProjInitialState with given projeciton', () => {+ let response = {+ id: 'some-test-projection',+ selected: proj+ };+ const initialState = getProjInitialState(config);+ expect(initialState.id).toBe(response.id);+ expect(initialState.selected.id).toBe(response.selected.id);+});+test('Default proj should be geographic', () => {+ let emptyConfig = {+ defaults: {}+ };+ let response = {+ id: 'geographic',+ selected: {}+ };+ const initialState = getProjInitialState(emptyConfig);+ expect(initialState.id).toBe(response.id);+});+test('mapLocationToProjState: Update proj:id key onload', () => {+ const state = {+ config: config,+ proj: {+ selected: {}+ }+ };+ const stateFromLocation = {+ proj: proj+ };+ const newState = mapLocationToProjState(null, stateFromLocation, state);+ expect(newState.proj.id).toBe('some-test-projection');+});